0

我正在尝试使用 python 中的scrapy 制作一个网络爬虫,它可以在您进行搜索时提取谷歌在右侧显示的信息

我使用的网址是:https ://www.google.com/search?q=la%20cuarta

在另一个问题中,我问了同样的问题(问题),有人建议我将 response.body 写入文件,但我得到一个空文件,当我尝试不同的 URL 时,这不会发生

这是我的代码:

import scrapy

class google1(scrapy.Spider):
    name = 'google1'

    def start_requests(self):
        urls = ['http://quotes.toscrape.com/page/1/',
        'http://quotes.toscrape.com/page/2/',
        'https://www.google.com/search?q=la%20cuarta',
        'https://docs.scrapy.org/en/latest/intro/tutorial.html']  
        for url in urls:
            yield scrapy.Request(url=url, callback=self.parse)

    def parse(self, response):
        page = response.url.split("/")[-2]
        filename = 'page-%s.html' % page
        with open(filename, 'wb') as f:
            f.write(response.body)
        self.log('Saved file %s' % filename)

它甚至没有从谷歌搜索中写入文件,但在scrapy shell response.body 中不为空

4

1 回答 1

2

好的,我测试了您的代码并且它可以工作,即蜘蛛下载所有页面,包括 googel 页面。您的问题可能出在设置中,请将这些添加到您的设置中:

USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:39.0) Gecko/20100101 Firefox/39.0'
ROBOTSTXT_OBEY = False
于 2019-05-28T15:59:24.953 回答