s717
2021-08-10 16:18
采纳率: 100%
浏览 52
已结题

python—用PIP安装了beautifulsoup库,使用的时候老是报错

用PIP安装了beautifulsoup库,使用的时候老是报错
代码如下:

import requests
from bs4 import BeautifulSoup
headers={
'user-agent':' Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36 Edg/92.0.902.67'
    }
res=requests.get('https://www.bilibili.com/',headers=headers)
soup=BeautifulSoup(res.text,'html.parser')
print(soup.prettify())

报错如下:

Traceback (most recent call last):
  File "C:\Users\sun\Desktop\1.py", line 6, in <module>
    res=requests.get('https://www.bilibili.com/',headers=headers)
  File "D:\Python\lib\site-packages\requests\api.py", line 75, in get
    return request('get', url, params=params, **kwargs)
  File "D:\Python\lib\site-packages\requests\api.py", line 61, in request
    return session.request(method=method, url=url, **kwargs)
  File "D:\Python\lib\site-packages\requests\sessions.py", line 528, in request
    prep = self.prepare_request(req)
  File "D:\Python\lib\site-packages\requests\sessions.py", line 456, in prepare_request
    p.prepare(
  File "D:\Python\lib\site-packages\requests\models.py", line 317, in prepare
    self.prepare_headers(headers)
  File "D:\Python\lib\site-packages\requests\models.py", line 451, in prepare_headers
    check_header_validity(header)
  File "D:\Python\lib\site-packages\requests\utils.py", line 978, in check_header_validity
    raise InvalidHeader("Invalid return character or leading space in header: %s" % name)
requests.exceptions.InvalidHeader: Invalid return character or leading space in header: user-agent
>>> 

操作系统是win10,IDLE,python3.8.4,已经更新了PIP,并且安装了要使用的第三方库

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

2条回答 默认 最新

  • 代码的灵魂是bug! 2021-08-10 16:34
    最佳回答

    不能带有空格

    img

    评论
    解决 无用
    打赏 举报
查看更多回答(1条)

相关推荐 更多相似问题