Scrapy xpath 没有解析它应该解析的内容

时间:2021-03-10 06:51:54

标签: python-3.x xpath scrapy

我已经测试了 xpath,测试结果显示了我想提取的所有引号,但是当我在 scrapy 中使用相同的 xpath 时,它一遍又一遍地给我相同的引号。但是当我从 xpath("//span[@class='text']/text()").get() 中删除“//”时,它给了我所有我想要的引号。我知道 // 意味着无论元素在哪里都可以找到它们,但是 // 在 for 循环期间似乎可以与其他元素一起正常工作。例如:row.xpath('//span/small[@itemprop="author"]/text()').get() 上面没有像引号那样一次又一次地给我相同的作者名字。那么,这里的问题似乎是什么? Tester results Scrapy Results

rank = 0

1 个答案:

答案 0 :(得分:0)

这只蜘蛛,它和你的一样,只是没有为我做一些印刷工作。

import scrapy

class QuotesSpider(scrapy.Spider):
    name = 'quotes'
    allowed_domains = ['www.quotes.toscrape.com/']
    start_urls = ['http://quotes.toscrape.com/']

    def parse(self, response):
        rows = response.xpath("//div[@class='quote']")

        for row in rows:
            quote = row.xpath("string(span[@itemprop='text'])").get()

            yield {'quote': quote}

输出

2021-03-10 09:51:16 [scrapy.core.scraper] DEBUG: Scraped from <200 http://quotes.toscrape.com/>
{'quote': '“The world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.”'}
2021-03-10 09:51:16 [scrapy.core.scraper] DEBUG: Scraped from <200 http://quotes.toscrape.com/>
{'quote': '“It is our choices, Harry, that show what we truly are, far more than our abilities.”'}
2021-03-10 09:51:16 [scrapy.core.scraper] DEBUG: Scraped from <200 http://quotes.toscrape.com/>
{'quote': '“There are only two ways to live your life. One is as though nothing is a miracle. The other is as though everything is a miracle.”'}
...

编辑 docs 有很好的解释。 // 将获取文档中的所有内容,与您的报价无关。不知道为什么它适用于作者。