【问题标题】:How to Scrape one of the span inside another span class?如何刮掉另一个跨度类中的一个跨度?
【发布时间】:2021-12-30 03:22:19
【问题描述】:
<span class="sim-posted">
        
            <span class="jobs-status covid-icon clearfix">
                <i class="covid-home-icon"></i>Work from Home 
            </span>
            <span>Posted few days ago</span>
            
    </span>

我想用文本“几天前发布”抓取最后一个跨度标签 我有代码,但它只用类刮掉第一个跨度

date_published=job.find('span',class_='sim-posted').span.text

【问题讨论】:

  • 工作对象是什么?

标签: python selenium beautifulsoup


【解决方案1】:

试试这个,它会在你到达的范围内找到另一个没有类的范围

date_published=job.find('span',class_='sim-posted').find("span", {"class": False}).text

【讨论】:

    【解决方案2】:

    要使用Selenium 将最后一个SPAN 标记与几天前发布 的文本一起抓取,您可以使用以下任一Locator Strategies: p>

    • 使用 csslast-child:

      span.sim-posted span:last-child
      
    • 使用 csslast-of-type:

      span.sim-posted span:last-of-type
      
    • 使用 cssnth-child():

      span.sim-posted span:nth-child(2)
      
    • 使用 cssnth-of-type():

      span.sim-posted span:nth-of-type(2)
      

    【讨论】:

      【解决方案3】:

      如果总是最后一个&lt;span&gt; 你可以选择css selector last-of-type:

      soup.select_one('span.sim-posted span:last-of-type').text
      

      示例

      import requests
      from bs4 import BeautifulSoup
      
      html='''
      <span class="sim-posted">
              
                  <span class="jobs-status covid-icon clearfix">
                      <i class="covid-home-icon"></i>Work from Home 
                  </span>
                  <span>Posted few days ago</span>
                  
          </span>
      '''
      soup = BeautifulSoup(html, "html.parser")
      
      soup.select_one('span.sim-posted span:last-of-type').text
      

      输出

      Posted few days ago
      

      另类

      您还可以使用 :-soup-contains 一个 css 伪类选择器来定位节点的文本。 Beautiful Soup 4.7.0 中添加了需要 SoupSieve 集成。

      soup.select_one('span.sim-posted span:-soup-contains("Posted")').text
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-12-05
        • 2020-01-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多