努力才能被爱慕 2018-03-25 07:07 采纳率: 100%
浏览 5476
已采纳

Python爬虫、requests库的get方法,带上headers后出现编码错误

目标网站:知乎
Pyrhon版本:3.6


agent = 'Mozilla/5.0 (Windows NT 6.1; W…) Gecko/20100101 Firefox/59.0'
header = {
    'HOST': 'www.zhihu.com',
    'Referer': 'https://www.zhihu.com',
    'User-Agent': agent
}

response = requests.get('https://www.zhihu.com', headers=header)

报错内容:

 Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Anaconda3\lib\site-packages\requests\api.py", line 72, in get
    return request('get', url, params=params, **kwargs)
  File "C:\Anaconda3\lib\site-packages\requests\api.py", line 58, in request
    return session.request(method=method, url=url, **kwargs)
  File "C:\Anaconda3\lib\site-packages\requests\sessions.py", line 518, in request
    resp = self.send(prep, **send_kwargs)
  File "C:\Anaconda3\lib\site-packages\requests\sessions.py", line 639, in send
    r = adapter.send(request, **kwargs)
  File "C:\Anaconda3\lib\site-packages\requests\adapters.py", line 438, in send
    timeout=timeout
  File "C:\Anaconda3\lib\site-packages\requests\packages\urllib3\connectionpool.py", line 600, in urlopen
    chunked=chunked)
  File "C:\Anaconda3\lib\site-packages\requests\packages\urllib3\connectionpool.py", line 356, in _make_request
    conn.request(method, url, **httplib_request_kw)
  File "C:\Anaconda3\lib\http\client.py", line 1239, in request
    self._send_request(method, url, body, headers, encode_chunked)
  File "C:\Anaconda3\lib\http\client.py", line 1280, in _send_request
    self.putheader(hdr, value)
  File "C:\Anaconda3\lib\http\client.py", line 1212, in putheader
    values[i] = one_value.encode('latin-1')
UnicodeEncodeError: 'latin-1' codec can't encode character '\u2026' in position 30: ordinal not in range(256)

\u2026好像是空格,看了下源码,好像是空格要转latin-1这种编码失败了,
我上面有空格的是agent,要用来伪装浏览器,这可怎么办,
而且在我看的那个知乎爬虫视频中,他也是有空格的,却不出错,这是我的环境有问题吗,
请大佬们能指点一下

  • 写回答

4条回答

      报告相同问题?

      相关推荐 更多相似问题

      悬赏问题

      • ¥15 ABAQUS简单的带传动系统运转不了
      • ¥15 关于git actions自动部署的问题
      • ¥25 小程序 view wx:for 循环太多时,如何在循环结束执行某个事件?
      • ¥15 曲率模态差matlab程序计算
      • ¥15 大概算是比较简单的坐标系旋转问题
      • ¥15 关于#python#的问题:安装完gym环境后
      • ¥15 关于稳像云台姿态控制中相机姿态误差表征
      • ¥15 求sm16306s驱动例程
      • ¥15 本地生活媒体平台口碑选品怎么获得权限
      • ¥15 R语言 回归树/袋装树/随机森林预测