【发布时间】: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