Scrapy bot和shell使用相同的xpath查询返回不同的结果。为什么?

时间:2015-11-10 18:47:46

标签: xpath scrapy scrapy-spider scrapy-shell

当我在scrapy bot和scrapy shell中执行相同的xpath查询时,我得到了不同的结果。

注意:我只是想学习scrapy并修改一些教程代码。请慢慢跟我走。

查询:

xpath('//div/div/div/ul/li/a/@href')

机器人:

import scrapy

from tutorial.items import DmozItem

class DmozSpider(scrapy.Spider):
    name = "dmoz"
    allowed_domains = ["lib-web.org"]
    start_urls = [
        "http://www.lib-web.org/united-states/public-libraries"
    ]

    def parse(self, response):
        for href in response.xpath('//div/div/div/ul/li/a/@href'):
            url = response.urljoin(href.extract())
            yield scrapy.Request(url, callback=self.parse_dir_contents)


    def parse_dir_contents(self, response):
        for sel in response.xpath('//ul/li'):
            item = DmozItem()
            item['title'] = sel.xpath('a/text()').extract()
            item['link'] = sel.xpath('a/@href').extract()
            item['desc'] = sel.xpath('p/text()').extract()
            yield item

DmozItem:

import scrapy

class DmozItem(scrapy.Item):
    title = scrapy.Field()
    link = scrapy.Field()
    desc = scrapy.Field()

我想要的只是指向州公共图书馆页面的链接(参见网页)。

这是shell显示的内容(这正是我想要的):

Admin$ scrapy shell http://www.lib-web.org/united-states/public-libraries
...snip...
In [1]: response.selector.xpath('//div/div/div/ul/li/a/@href')
Out[1]: 
[<Selector xpath='//div/div/div/ul/li/a/@href' data=u'/united-states/public-libraries/alabama/'>,
 <Selector xpath='//div/div/div/ul/li/a/@href' data=u'/united-states/public-libraries/alaska/'>,
...snip. for brevity...
 <Selector xpath='//div/div/div/ul/li/a/@href' data=u'/united-states/public-libraries/wisconsi'>,
 <Selector xpath='//div/div/div/ul/li/a/@href' data=u'/united-states/public-libraries/wyoming/'>]

当蜘蛛运行相同的查询时,我得到了我不想要的其他href选择。

一些例子:

2015-11-10 13:27:52 [scrapy] DEBUG: Scraped from <200 http://www.lib-web.org/united-states/public-libraries/alabama/>
{'desc': [], 'link': [u'http://www.dirbuzz.com'], 'title': [u'DirBuzz.com']}
2015-11-10 13:27:52 [scrapy] DEBUG: Scraped from <200 http://www.lib-web.org/united-states/public-libraries/alabama/>
{'desc': [], 'link': [u'http://www.dirville.com'], 'title': [u'DirVille']}
2015-11-10 13:27:52 [scrapy] DEBUG: Scraped from <200 http://www.lib-web.org/united-states/public-libraries/alabama/>
{'desc': [], 'link': [u'http://www.duddoo.com'], 'title': [u'Duddoo.net']}

据我所知,机器人返回的许多元素/链接不适合 xpath选择器。这是怎么回事?有人可以解释一下我做错了什么吗?

非常感谢!

1 个答案:

答案 0 :(得分:2)

查看您的parse功能。这一行response.xpath('//div/div/div/ul/li/a/@href')将为您提供所需的状态库的所有链接列表。现在,您将使用此行yield scrapy.Request(url, callback=self.parse_dir_contents)遍历所有已删除链接并跟踪链接。然后您的机器人正在回调函数parse_dir_contents。在此函数中,您的机器人正在选择xpath //ul/li中存在的所有元素。因此,您看到的输出链接实际上出现在后面的链接页面中,而不是start_url's页面。这就是shell输出和蜘蛛输出之间存在差异的原因。 shell输出仅显示您传递给它的URL的链接。您可以访问网址http://www.lib-web.org/united-states/public-libraries/alabama/并检查其是否包含此网址http://www.dirbuzz.com来交叉检查您的搜索结果。

相关问题