正在向Scrapy Spid添加标头

2024-09-28 23:26:48 发布

您现在位置:Python中文网/ 问答频道 /正文

对于一个项目,我运行了大量的垃圾请求的某些搜索词。这些请求使用相同的搜索词,但时间范围不同,如下面URL中的日期所示。在

尽管URL引用的日期和页面不同,但我收到的值与所有请求的输出值相同。它看起来像是脚本正在获取第一个值,并将相同的输出分配给所有后续请求。在

import scrapy

 class QuotesSpider(scrapy.Spider):
    name = 'quotes'
    allowed_domains = ['google.com']
    start_urls = ['https://www.google.com/search?q=Activision&biw=1280&bih=607&source=lnt&tbs=cdr%3A1%2Ccd_min%3A01%2F01%2F2004%2Ccd_max%3A12%2F31%2F2004&tbm=nws',
                  'https://www.google.com/search?q=Activision&biw=1280&bih=607&source=lnt&tbs=cdr%3A1%2Ccd_min%3A01%2F01%2F2005%2Ccd_max%3A12%2F31%2F2005&tbm=nws',
                  'https://www.google.com/search?q=Activision&biw=1280&bih=607&source=lnt&tbs=cdr%3A1%2Ccd_min%3A01%2F01%2F2006%2Ccd_max%3A12%2F31%2F2006&tbm=nws',
    ]

    def parse(self, response):
        item = {
            'search_title': response.css('input#sbhost::attr(value)').get(),
            'results': response.css('#resultStats::text').get(),
            'url': response.url,
        }
        yield item

我找到一条线discussing a similar problem with BeautifulSoup。解决方案是在脚本中添加头,从而使其使用浏览器作为用户代理:

^{pr2}$

在scrayseems to be different though中应用头的方法。有人知道如何将它最好地包含在Scrapy中吗,尤其是对同时包含多个url的start_urls的引用?在


Tags: httpscomurlsourcesearchresponsewwwgoogle
2条回答

你不需要在这里修改标题。您需要设置Scrapy允许您直接执行的用户代理。在

import scrapy

class QuotesSpider(scrapy.Spider):
    # ...
    user_agent = 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36'
    # ...

现在您将得到如下输出:

^{pr2}$

根据Scrapy 1.7.3 document。你的头不会像其他人一样通用。它应该是相同的网站,你正在刮。您将从控制台网络选项卡了解标题。在

像下面这样添加它们并打印响应。在

# -*- coding: utf-8 -*-
import scrapy
#import logging

class AaidSpider(scrapy.Spider):
    name = 'aaid'

    def parse(self, response):
        url = "https://www.eventscribe.com/2019/AAOMS-CSIOMS/ajaxcalls/PresenterInfo.asp?efp=SVNVS1VRTEo4MDMx&PresenterID=597498&rnd=0.8680339"

        # Set the headers here. 
        headers =  {
            'Accept': '*/*',
            'Accept-Encoding': 'gzip, deflate, br',
            'Accept-Language': 'en-GB,en-US;q=0.9,en;q=0.8',
            'Connection': 'keep-alive',
            'Host': 'www.eventscribe.com',
            'Referer': 'https://www.eventscribe.com/2018/ADEA/speakers.asp?h=Browse%20By%20Speaker',
            'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36',
            'X-Requested-With': 'XMLHttpRequest'
        }
# Send the request
        scrapy.http.Request(url, method='GET' , headers = headers,  dont_filter=False)

        print(response.body) #If the response is HTML
        #If the response is json ; import json
        #jsonresponse = json.loads(response.body_as_unicode())
        #print jsonresponse

相关问题 更多 >