【问题标题】:Changing Scrapy/Splash user agent更改 Scrapy/Splash 用户代理
【发布时间】:2018-02-12 23:36:17
【问题描述】:

如何使用 Splash 为 Scrapy 设置用户代理,方法如下:

import requests
from bs4 import BeautifulSoup

ua = {"User-Agent":"Mozilla/5.0"}
url = "http://www.example.com"
page = requests.get(url, headers=ua)
soup = BeautifulSoup(page.text, "lxml")

我的蜘蛛看起来会像这样:

import scrapy
from scrapy_splash import SplashRequest


class ExampleSpider(scrapy.Spider):
        name = "example"
        allowed_domains = ["example.com"]
        start_urls = ["https://www.example.com/"]

        def start_requests(self):
            for url in self.start_urls:
                yield SplashRequest(
                    url,
                    self.parse,
                    args={'wait': 0.5}
                )

【问题讨论】:

  • 你试过SplashRequest的splash_headers参数了吗?

标签: python-3.x web-scraping scrapy splash-screen


【解决方案1】:

您需要设置user_agent 属性来覆盖默认用户代理:

class ExampleSpider(scrapy.Spider):
    name = 'example'
    user_agent = 'Mozilla/5.0'

在这种情况下,UserAgentMiddleware(即enabled by default)会将USER_AGENT 设置值覆盖为'Mozilla/5.0'

您还可以覆盖每个请求的标头:

scrapy_splash.SplashRequest(url, headers={'User-Agent': custom_user_agent})

【讨论】:

  • 但是,据我了解,Splash 没有考虑 Scrapy 设置。
  • @zinyosrim,我刚刚使用 httpbin.org/headers URL 检查了它,user_agent 肯定会影响 httpbin 响应中的 User-Agent 值。
【解决方案2】:

正确的方法是更改​​启动脚本以包含它...不过,如果它也能正常工作,则不要将它添加到蜘蛛中。

http://splash.readthedocs.io/en/stable/scripting-ref.html?highlight=agent

【讨论】:

    【解决方案3】:

    如果你使用 pure splash(不是 scrapy-splash 包),你可以只使用 'User-Agent' 键传递 headers 参数。并且这个页面上的请求都将使用这个用户代理。

    https://splash.readthedocs.io/en/stable/api.html?highlight=User-Agent

    这是一个例子:

    import requests
    import json
    
    headers = {
        'User-Agent': 'Mozilla/5.0',
    }
    param = {
        'url': your_aim_url,
        'headers': headers,
        'html': 1,
        'har': 1,
        'response_body': 1,
    }
    session = requests.Session()
    session.headers.update({'Content-Type': 'application/json'})
    response = self.session.post(url='http://127.0.0.1:8050/render.json', json=param)
    response_json = json.loads(response.text, encoding='utf-8')
    print(response_json.get('html'))  # page html
    print(response_json.get('har'))  # har with respose body. if do not want respose body, set 'response_body' to 0
    

    你可以检查 har 中的请求头,看看 user-agent 是否正确。

    【讨论】:

      猜你喜欢
      • 2017-09-24
      • 2018-06-30
      • 1970-01-01
      • 2020-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多