【问题标题】:How to randomize Header with Users Agent list?如何使用用户代理列表随机化标题?
【发布时间】:2022-06-13 20:10:12
【问题描述】:

我有一个问题,

在我的脚本 .py 中有:

    headers = {'Connection': 'keep-alive',
              'Cache-Control': 'max-age=0',
              'Upgrade-Insecure-Requests': '1',
              'User-Agent': {agents},
              'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
              'Accept-Encoding': 'gzip, deflate',
              'Accept-Language': 'en-US,en;q=0.9,fr;q=0.8',
              'referer': 'bing.com'}

在 .json 文件上

    { 
      "user_agent_list": [
          "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36",
          "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36"
      ]
    }

当我发送请求时:

find_file = (grequests.get(url_a, headers={headers}, timeout=None, stream=True, verify=False, allow_redirects=False) for url_a in [f'{site_link}{x}' for x in file_rootl])

我怎样才能为每个请求随机化 headers={headers} ?当然“对于 user_agent_list 中的代理

更好:

'User-Agent': {agents},我需要在标题内随机化...

有什么想法吗? 谢谢 最大

【问题讨论】:

    标签: python-3.x random request-headers


    【解决方案1】:

    你可以通过一个随机函数来获得一个随机的:

    import random
    def get_headers():
        headers = {'Connection': 'keep-alive',
                  'Cache-Control': 'max-age=0',
                  'Upgrade-Insecure-Requests': '1',
                  'User-Agent': {random.choice(user_agent_list)},
                  'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
                  'Accept-Encoding': 'gzip, deflate',
                  'Accept-Language': 'en-US,en;q=0.9,fr;q=0.8',
                  'referer': 'bing.com'}
        return headers
    
    #then
    find_file = (grequests.get(url_a, headers={get_headers()}, timeout=None, stream=True, verify=False, allow_redirects=False) for url_a in [f'{site_link}{x}' for x in file_rootl])
    

    user_agent_list 具有从 json 导入的值。

    【讨论】:

      猜你喜欢
      • 2019-08-15
      • 1970-01-01
      • 2018-12-18
      • 2016-04-06
      • 2011-12-06
      • 2018-07-05
      • 1970-01-01
      • 2019-05-01
      • 1970-01-01
      相关资源
      最近更新 更多