CD84380973 发表于 2020-3-31 19:46:39

输出报错怎么办

代码复制的课后作业
import urllib.request
import re
from bs4 import BeautifulSoup

def main():
    url = "http://baike.baidu.com/view/284853.htm"
    response = urllib.request.urlopen(url)
    html = response.read()
    soup = BeautifulSoup(html, "html.parser") # 使用 Python 默认的解析器
   
    for each in soup.find_all(href=re.compile("view")):
      print(each.text, "->", ''.join(["http://baike.baidu.com", each["href"]]))
      # 上边用 join() 不用 + 直接拼接,是因为 join() 被证明执行效率要高很多

if __name__ == "__main__":
    main()


报错内容
Traceback (most recent call last):
File "C:\Users\39436\Desktop\python练习\55-1.py", line 16, in <module>
    main()
File "C:\Users\39436\Desktop\python练习\55-1.py", line 9, in main
    soup = BeautifulSoup(html, "html.parser") # 使用 Python 默认的解析器
File "C:\Users\39436\AppData\Local\Programs\Python\Python38\lib\site-packages\bs4\__init__.py", line 153, in __init__
    builder = builder_class()
File "C:\Users\39436\AppData\Local\Programs\Python\Python38\lib\site-packages\bs4\builder\_htmlparser.py", line 39, in __init__
    return super(HTMLParserTreeBuilder, self).__init__(*args, **kwargs)
TypeError: __init__() got an unexpected keyword argument 'strict'

百度后在CMD里python -m pip install --upgrade pip将PIP更新到最新版20.0.02还是不行
CMD显示Successfully installed pip-20.0.2

小小小菜菜菜 发表于 2020-3-31 20:45:30

html = response.read()改成html = response.read().encode(‘utf-8’)试试

CD84380973 发表于 2020-3-31 20:50:07

小小小菜菜菜 发表于 2020-3-31 20:45
html = response.read()改成html = response.read().encode(‘utf-8’)试试

AttributeError: 'bytes' object has no attribute 'encode'

改了以后报这个错了

CD84380973 发表于 2020-3-31 21:06:04

谁能帮帮我?

小小小菜菜菜 发表于 2020-3-31 22:01:44

我这边用你的代码是OK的,建议你看看网络环境或者重启电脑再试试。
页: [1]
查看完整版本: 输出报错怎么办