python - 官方scrapy例子出错?

标签 python scrapy

尝试了出现在 documentation page 上的示例 scrapy 用法 (名称下的示例:从单个回调中返回多个请求和项目)

我只是将域更改为指向一个真实的网站:

import scrapy

class MySpider(scrapy.Spider):
    name = 'huffingtonpost'
    allowed_domains = ['huffingtonpost.com/']
    start_urls = [
        'http://www.huffingtonpost.com/politics/',
        'http://www.huffingtonpost.com/entertainment/',
        'http://www.huffingtonpost.com/media/',
    ]

    def parse(self, response):
        for h3 in response.xpath('//h3').extract():
            yield {"title": h3}

        for url in response.xpath('//a/@href').extract():
            yield scrapy.Request(url, callback=self.parse)

但得到了 ValuError,如 this gist 中所述. 有什么想法吗?

最佳答案

一些提取的链接是相对的(例如,/news/hillary-clinton/)。 您应该将其转换为绝对 (http://www.huffingtonpost.com/news/hillary-clinton/

import scrapy

class MySpider(scrapy.Spider):
    name = 'huffingtonpost'
    allowed_domains = ['huffingtonpost.com/']
    start_urls = [
        'http://www.huffingtonpost.com/politics/',
        'http://www.huffingtonpost.com/entertainment/',
        'http://www.huffingtonpost.com/media/',
    ]

    def parse(self, response):
        for h3 in response.xpath('//h3').extract():
            yield {"title": h3}

        for url in response.xpath('//a/@href').extract():
            if url.startswith('/'):
                # transform url into absolute
                url = 'http://www.huffingtonpost.com' + url
            if url.startswith('#'):
                # ignore href starts with #
                continue
            yield scrapy.Request(url, callback=self.parse)

关于python - 官方scrapy例子出错?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32906873/

相关文章:

python - 加载模块时使用 sys.path.insert(0, path) 和 sys.path(append) 的效果

python - 如何使用给定坐标在图像中绘制一个点

python - 计算宏观/微观平均值

python - Scrapy 在基本示例上崩溃(无法运行)

python - xpath当兄弟不是元素时如何获取文本

python - 如何在 pyspark 列表达式中引用名称中带有连字符的列?

python - 将数据分箱到相同大小的箱中

python - Scrapy 获取跨多行和嵌套元素内的文本

javascript - scrapy-splash 用于渲染 javascript

python - scrapy如何正确使用Rules、restrict_xpaths抓取解析URL?