【问题标题】:How to use the Rule class in scrapy如何在scrapy中使用Rule类
【发布时间】:2015-03-20 23:41:21
【问题描述】:

我正在尝试使用 Rule 类转到我的爬虫中的下一页。这是我的代码

from scrapy.contrib.spiders import CrawlSpider,Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from crawler.items import GDReview


class GdSpider(CrawlSpider):
    name = "gd"
    allowed_domains = ["glassdoor.com"]
    start_urls = [
        "http://www.glassdoor.com/Reviews/Johnson-and-Johnson-Reviews-E364_P1.htm"
    ]

    rules = (

        # Extract next links and parse them with the spider's method parse_item
        Rule(SgmlLinkExtractor(restrict_xpaths=('//li[@class="next"]/a/@href',)), follow= True)
    )


    def parse(self, response):
        company_name = response.xpath('//*[@id="EIHdrModule"]/div[3]/div[2]/p/text()').extract()

        '''loop over every review in this page'''
        for sel in response.xpath('//*[@id="EmployerReviews"]/ol/li'):
            review = Item()
            review['company_name'] = company_name
            review['id'] = str(sel.xpath('@id').extract()[0]).split('_')[1] #sel.xpath('@id/text()').extract()
            review['body'] = sel.xpath('div/div[3]/div/div[2]/p/text()').extract()
            review['date'] = sel.xpath('div/div[1]/div/time/text()').extract()
            review['summary'] = sel.xpath('div/div[2]/div/div[2]/h2/tt/a/span/text()').extract()

            yield review

我的问题是关于规则部分。在此规则中,提取的链接不包含域名。例如,它将返回类似 "/Reviews/Johnson-and-Johnson-Reviews-E364_P1.htm"

如何确保我的爬虫将域附加到返回的链接?

谢谢

【问题讨论】:

    标签: python web-crawler scrapy scrapy-spider


    【解决方案1】:

    您可以确定,因为这是 Scrapy (source code) 中链接提取器的默认行为。

    此外,restrict_xpaths 参数不应指向 @href 属性,而应指向 a 元素或具有 a 元素作为后代的容器。另外,restrict_xpaths 可以定义为字符串。

    换句话说,替换:

    restrict_xpaths=('//li[@class="next"]/a/@href',)
    

    与:

    restrict_xpaths='//li[@class="next"]/a'
    

    另外,你需要从SgmlLinkExtractor切换到LxmlLinkExtractor

    基于 SGMLParser 的链接提取器是无人维护的,它的用法是 灰心。如果您建议迁移到 LxmlLinkExtractor 仍在使用 SgmlLinkExtractor。

    就我个人而言,我通常使用LinkExractor 快捷方式到LxmlLinkExtractor

    from scrapy.contrib.linkextractors import LinkExtractor
    

    总而言之,这就是我在rules 中所拥有的:

    rules = [
        Rule(LinkExtractor(restrict_xpaths='//li[@class="next"]/a'), follow=True)
    ]
    

    【讨论】:

    • “加号,restrict_xpaths 可以定义为字符串”是什么意思。 ??它们必须是有效的 xpath 对吗?
    猜你喜欢
    • 2018-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-17
    • 1970-01-01
    • 2019-01-10
    相关资源
    最近更新 更多