Scrapy抓取同类名内容
我正在使用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()
但是它却返回了所有的内容。任何帮助都会非常有用!!
4 个回答
-1
使用 xpath
可以找到所有具有相同类名的
标签,接下来,你可以对这些标签进行循环处理,以获取结果(适用于scrapy):
divs = response.xpath('//div[@class="full class name"]')
for div in divs:
if div.css("div.class"):
0
在编程中,有时候我们会遇到一些问题,比如代码运行不正常或者出现错误。这些问题可能是因为我们没有正确理解某些概念,或者在写代码的时候犯了一些小错误。
比如,有些人可能会在使用某个功能时,忘记先初始化它,或者没有正确设置参数。这就像是你在做饭时,忘记先把锅加热,结果菜就做不好。
另外,调试代码也很重要。调试就是找出代码中哪里出错了,像是侦探一样去查找线索。通过仔细检查代码,逐行运行,看看哪里不对,我们就能找到问题并解决它。
总之,编程就像是解决谜题,有时候需要耐心和细心,才能找到正确的答案。
'(//div[@class = "same_name"])[1]/text()'
0
你可以使用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
这样就可以完成工作了。
1
好的,这个方法对我有效。
print desc[0]
它给我返回了这是第一个div,正是我想要的结果。