【问题标题】:Scrapy Crawler working in shell but not in codeScrapy Crawler 在 shell 中工作,但不在代码中
【发布时间】:2018-01-12 18:36:32
【问题描述】:

您好,我正在尝试从 scrapy 构建一个简单的爬虫。

代码在 scrapy shell 中运行良好,但是当我通过控制台运行它时,它不会向 json 文件写入任何内容。

我从项目顶层目录运行它

scrapy crawl filemare -o filemare.json


import scrapy


class FilemareSpider(scrapy.Spider):
    name = "filemare"
    allowed_domains = ['https://filemare.com/']
    start_urls = ["https://filemare.com/en-
                   us/search/firmware%20download/632913359"]

    def parse(self, response):
        items = response.xpath('//div[@class="f"]/text()').extract()
        #items = response.css('div.f::text').extract()

        for url in items:
            print(url)
            yield url

【问题讨论】:

    标签: python scrapy web-crawler


    【解决方案1】:

    parse 方法必须返回 dict、Scrapy ItemRequest 对象(参见 documentation)。在您的情况下,您会产生一个字符串。如果你运行蜘蛛,你会在输出中看到一个错误。

    把代码的对应部分改成这样:

    ...
    def parse(self, response):
        items = response.xpath('//div[@class="f"]/text()').extract()
    
        for url in items:
            print(url)
            yield {'url': url}
    

    【讨论】:

    • 谢谢,这很有用。但是由于 robots.txt 文件,我的爬虫被禁用了。需要将设置文件更改为 ROBOTSTXT_OBEY = False
    • 真的吗?当我自己尝试您的代码时,爬行继续进行并且产生是唯一的问题。
    猜你喜欢
    • 2018-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-29
    • 1970-01-01
    相关资源
    最近更新 更多