【问题标题】:How do I scrape data from a tag belonging to the same label and the same class? BeautifulSoup如何从属于同一标签和同一类的标签中抓取数据?美丽汤
【发布时间】:2021-12-24 18:04:03
【问题描述】:

我有一个具有相同标签和相同名称(属性)的标签。 这是我的代码

first_movie.find('p',{'class' : 'sort-num_votes-visible'})

这是我的输出

<p class="sort-num_votes-visible">
<span class="text-muted">Votes:</span>
<span data-value="978272" name="nv">978,272</span>
<span class="ghost">|</span> <span class="text-muted">Gross:</span>
<span data-value="858,373,000" name="nv">$858.37M</span>
</p>

我正在到达 span 标记这段代码;

first_movie.find('span', {'name':'nv',"data-value": True})

978272 --> 输出

但我想用命名为 nv ($858.37M) 来达到另一个价值。 我的代码只得到这个值(978,272),因为标签名称彼此相等(name = nv)

【问题讨论】:

    标签: python html web-scraping beautifulsoup scrapy


    【解决方案1】:

    你已经接近了。

    尝试使用find_all,然后抓取最后一个元素。

    例如:

    from bs4 import BeautifulSoup
    
    html_sample = '''
    <p class="sort-num_votes-visible">
    <span class="text-muted">Votes:</span>
    <span data-value="978272" name="nv">978,272</span>
    <span class="ghost">|</span> <span class="text-muted">Gross:</span>
    <span data-value="858,373,000" name="nv">$858.37M</span>
    </p>
    '''
    
    soup = (
        BeautifulSoup(html_sample, "lxml")
        .find_all("span", {'name':'nv',"data-value": True})
    )
    print(soup[-1].getText())
    

    输出:

    $858.37M
    

    【讨论】:

      【解决方案2】:

      如果你到达 p 标签中的所有 span,你可以像 list 一样使用它们,并使用 index 到达最后一个 div。

      movies = soup.find('p',{'class' : 'sort-num_votes-visible'})
      
      my_movie = movies.findAll('span')
      
      my_span = my_movie[3].text
      

      【讨论】:

        猜你喜欢
        • 2019-04-13
        • 1970-01-01
        • 2018-07-18
        • 2021-06-18
        • 2020-07-16
        • 2014-10-16
        • 1970-01-01
        • 1970-01-01
        • 2021-12-08
        相关资源
        最近更新 更多