[英]Scrapy scrape content having same class name
我正在使用 scrapy 从特定网站抓取和抓取数据。 爬网工作正常,但我在从具有相同类名的 div 中抓取内容时遇到问题。 例如:
<div class="same_name">
this is the 1st div
</div>
<div class="same_name">
this is the 2nd div
</div>
<div class="same_name">
this is the 3rd div
</div>
我只想检索这是第一个 div 。 我使用的代码是:
desc = hxs.select('//div[@class = "same_name"]/text()').extract()
但它返回了我所有的内容。 任何帮助都会非常有帮助!
好的,这个对我有用。
print desc[0]
它返回给我,这是我想要的第一个 div 。
您可以使用 BeautifulSoup。 它是一个很棒的 html 解析器。
from BeautifulSoup import BeautifulSoup
html = """
<div class="same_name">
this is the 1st div
</div>
<div class="same_name">
this is the 2nd div
</div>
<div class="same_name">
this is the 3rd div
</div>
"""
soup = BeautifulSoup(html)
print soup.text
那应该做的工作。
使用xpath
,您将获得具有相同类的所有 div,此外,您可以循环它们以获得结果(对于 scrapy):
divs = response.xpath('//div[@class="full class name"]')
for div in divs:
if div.css("div.class"):
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.