Scrapy刮擦具有相同类名的内容

bxgwgixi  于 2022-11-09  发布在  其他
关注(0)|答案(3)|浏览(163)

我正在使用scrapy从一个特定的webiste抓取数据。抓取工作正常,但是当从div抓取具有相同类名的内容时,我遇到了问题。例如:

  1. <div class="same_name">
  2. this is the 1st div
  3. </div>
  4. <div class="same_name">
  5. this is the 2nd div
  6. </div>
  7. <div class="same_name">
  8. this is the 3rd div
  9. </div>

我只想检索这是第一个div。我使用的代码是:

  1. desc = hxs.select('//div[@class = "same_name"]/text()').extract()

但是它会把所有的内容都返回给我。任何帮助都会很有帮助!!

kr98yfug

kr98yfug1#

好吧,这个对我有用。

  1. print desc[0]

它返回给我这是第一个div这是我想要的。

ie3xauqp

ie3xauqp2#

你可以使用BeautifulSoup,它是一个很棒的html解析器。

  1. from BeautifulSoup import BeautifulSoup
  2. html = """
  3. <div class="same_name">
  4. this is the 1st div
  5. </div>
  6. <div class="same_name">
  7. this is the 2nd div
  8. </div>
  9. <div class="same_name">
  10. this is the 3rd div
  11. </div>
  12. """
  13. soup = BeautifulSoup(html)
  14. print soup.text

这样就行了。

展开查看全部
nmpmafwu

nmpmafwu3#

使用xpath,你将得到所有具有相同类的div,进一步,你可以在它们上循环以得到结果(对于scrapy):

  1. divs = response.xpath('//div[@class="full class name"]')
  2. for div in divs:
  3. if div.css("div.class"):

相关问题