【问题标题】:TypeError: request() got an unexpected keyword argument 'header' - when i use header,403 error - without headerTypeError: request() got an unexpected keyword argument 'header' - 当我使用标头时,403 错误 - 没有标头
【发布时间】:2020-04-16 21:20:27
【问题描述】:

我正在尝试从this 网站抓取信息,但不断获得状态码:403, 所以尝试使用 header 但得到 TypeError: request() got an unexpected keyword argument 'header'

代码:

import requests

head = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:71.0) Gecko/20100101 Firefox/71.0'}
url = "https://www.accuweather.com/en/bd/dhaka/28143/current-weather/28143"
pageObj = requests.get(url, header = head)
print("Status code: " + str(pageObj.status_code)) # *for testing purpose*

错误:

Traceback (most recent call last):
  File "F:/Python/PyCharm Community Edition 2019.2.3/Workshop/WEB_SCRAPING/test2.py", line 6, in <module>
    pageObj = requests.get(url, header = head)
  File "F:\Python\PyCharm Community Edition 2019.2.3\Workshop\WEB_SCRAPING\venv\lib\site-packages\requests\api.py", line 75, in get
    return request('get', url, params=params, **kwargs)
  File "F:\Python\PyCharm Community Edition 2019.2.3\Workshop\WEB_SCRAPING\venv\lib\site-packages\requests\api.py", line 60, in request
    return session.request(method=method, url=url, **kwargs)
TypeError: request() got an unexpected keyword argument 'header'

header from firefox dev tool

我做错了什么?

【问题讨论】:

    标签: python html python-requests http-status-code-403


    【解决方案1】:

    参数的名称是headers,而不是header。请参阅docs。

    使用pageObj = requests.get(url, headers=head)

    【讨论】:

      【解决方案2】:

      你需要在params中设置header:

      import requests
      head = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:71.0) Gecko/20100101 Firefox/71.0'}
      url = "https://www.accuweather.com/en/bd/dhaka/28143/current-weather/28143"
      PARAMS = {'header':head} 
      pageObj = requests.get(url, params = PARAMS)
      

      【讨论】:

      • “参数”是做什么用的?我知道标头用于某种代理
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-19
      • 1970-01-01
      • 2022-01-12
      • 2015-09-23
      • 2021-06-03
      • 1970-01-01
      相关资源
      最近更新 更多