【问题标题】:Targeting the third list item with beautiful soup用漂亮的汤瞄准第三个列表项
【发布时间】:2020-11-25 01:02:24
【问题描述】:

我正在使用 Beautiful Soup 抓取网站,但在尝试定位嵌套在 li 标签内的 span 标签中的项目时遇到问题。我试图抓取的网站对每个列表项使用相同的类,这使得它变得更加困难。 HTML 看起来像这样:

<div class="bigger-container">
<div class="smaller-container">
<ul class="ulclass">
<li>
<span class="description"></span>
<span class="item"></span>
</li>
<li>
<span class="description"></span>
<span class="item"></span>
</li>
<li>
<span class="description"></span>
<span class="item">**This is the only tag I want to scrape**</span>
</li>
<li>
<span class="description"></span>
<span class="item"></span>
</li>
</ul>

我的第一个想法是尝试使用“nth-of-type() 来定位它 - 我发现了一个类似的问题 here 但它没有帮助。我已经尝试使用它一段时间了,但我的代码基本上是这样的:

import requests
from bs4 import BeautifulSoup

url = 'url of website I'm scraping'
headers = {User-Agent Header}

for page in range(1):
    r = requests.get(url, headers = headers)
    soup = BeautifulSoup(r.content, features="lxml")

    scrape = soup.find_all('div', class_ = 'even_bigger_container_not_included_in_html_above') 

    for item in scrape:
        condition = soup.find('li:nth-of-type(2)', 'span:nth-of-type(1)').text
        print(condition)

非常感谢任何帮助!

【问题讨论】:

    标签: python web-scraping beautifulsoup


    【解决方案1】:

    要使用 CSS 选择器,请使用 select() 方法,而不是 find()

    所以要获得第三个 &lt;li&gt;,请使用 li:nth-of-type(3) 作为 CSS 选择器:

    from bs4 import BeautifulSoup
    
    
    html = """<div class="bigger-container">
    <div class="smaller-container">
    <ul class="ulclass">
    <li>
    <span class="description"></span>
    <span class="item"></span>
    </li>
    <li>
    <span class="description"></span>
    <span class="item"></span>
    </li>
    <li>
    <span class="description"></span>
    <span class="item">**This is the only tag I want to scrape**</span>
    </li>
    <li>
    <span class="description"></span>
    <span class="item"></span>
    </li>
    </ul>"""
    
    
    soup = BeautifulSoup(html, "html.parser")
    
    
    print(soup.select_one("li:nth-of-type(3)").get_text(strip=True))
    

    输出:

    **This is the only tag I want to scrape**
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-20
      • 2019-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-19
      • 1970-01-01
      相关资源
      最近更新 更多