gpt4 book ai didi

python - 通过bs4打印抓取的网页时出错

转载 作者:行者123 更新时间:2023-12-01 04:54:10 25 4
gpt4 key购买 nike

代码:

import requests
import urllib
from bs4 import BeautifulSoup

page1 = urllib.request.urlopen("http://en.wikipedia.org/wiki/List_of_human_stampedes")
soup = BeautifulSoup(page1)
print(soup.get_text())
print(soup.prettify())

错误:

 Traceback (most recent call last):
File "C:\Users\sony\Desktop\Trash\Crawler Try\try2.py", line 9, in <module>
print(soup.get_text())
File "C:\Python34\lib\encodings\cp1252.py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u014d' in position 10487: character maps to <undefined>

我认为问题主要出在 urlib 包上。这里我使用 urllib3 包。他们将 urlopen 语法从 2 版本更改为 3 版本,这可能是错误的原因。但话虽这么说,我只包含了最新的语法。Python版本3.4

最佳答案

由于您正在导入requests,因此您可以使用它来代替 urllib,如下所示:

import requests
from bs4 import BeautifulSoup

page1 = requests.get("http://en.wikipedia.org/wiki/List_of_human_stampedes")
soup = BeautifulSoup(page1.text)
print(soup.get_text())
print(soup.prettify())

您的问题是 python 无法对您正在抓取的页面中的字符进行编码。有关更多信息,请参阅此处:https://stackoverflow.com/a/16347188/2638310

由于维基百科页面采用 UTF-8 格式,因此 BeautifulSoup 似乎错误地猜测了编码。尝试在代码中传递 from_encoding 参数,如下所示:

soup = BeautifulSoup(page1.text, from_encoding="UTF-8")

有关 BeautifulSoup 中编码的更多信息,请查看此处:http://www.crummy.com/software/BeautifulSoup/bs4/doc/#encodings

关于python - 通过bs4打印抓取的网页时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27817250/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com