1

当我在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

Dmoz项目:

import scrapy

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

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

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

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 选择器。这是怎么回事?有人可以解释我做错了什么吗?

非常感谢!

4

1 回答 1

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 的链接。您可以通过访问 url 来交叉检查您的结果http://www.lib-web.org/united-states/public-libraries/alabama/并检查它是否包含此 url http://www.dirbuzz.com

于 2015-11-10T19:26:44.687 回答