gpt4 book ai didi

python - BeautifulSoup webscraper 中的 UnicodeEncodeError

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

对于一个简单的网络抓取工具,我遇到了以下代码的 unicode 编码错误。

print 'JSON scraper initializing'

from bs4 import BeautifulSoup
import json
import requests
import geocoder


# Set page variable
page = 'https://www.bandsintown.com/?came_from=257&page='
urlBucket = []
for i in range (1,3):
uniqueUrl = page + str(i)
urlBucket.append(uniqueUrl)

# Build response container
responseBucket = []

for i in urlBucket:
uniqueResponse = requests.get(i)
responseBucket.append(uniqueResponse)


# Build soup container
soupBucket = []
for i in responseBucket:
individualSoup = BeautifulSoup(i.text, 'html.parser')
soupBucket.append(individualSoup)


# Build events container
allSanFranciscoEvents = []
for i in soupBucket:
script = i.find_all("script")[4]

eventsJSON = json.loads(script.text)

allSanFranciscoEvents.append(eventsJSON)


with open("allSanFranciscoEvents.json", "w") as writeJSON:
json.dump(allSanFranciscoEvents, writeJSON, ensure_ascii=False)
print ('end')

奇怪的是,有时,这段代码可以工作,并且不会给出错误。它与代码的 for i in range 行有关。例如,如果我输入 (2,4) 作为范围,它就可以正常工作。如果我将其更改为 1,3, 它会显示:

UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 12: ordinal not in range(128)

谁能告诉我如何在我的代码中解决这个问题?如果我打印 allSanFranciscoEvents,它会读取所有数据,因此我相信问题发生在最后一段代码中,即 JSON 转储。非常感谢。

最佳答案

最佳修复

使用Python 3! Python 2 是 going EOL很快。今天用旧版 Python 编写的新代码的保质期非常短。

为了让您的代码在 python 3 中工作,我必须更改的唯一一件事是调用 print() 函数而不是 print 关键字。然后,您的示例代码就可以正常运行,没有任何错误。

坚持使用 Python 2

The odd thing is the sometimes, this code works, and doesn't give an error. It has to do with the for i in range line of the code. For example, if I put in (2,4) for the range, it works fine.

这是因为您请求具有不同范围的不同页面,并且并非每个页面都有无法使用 ascii 编解码器转换为 str 的字符。我必须转到响应的第 5 页才能得到与您相同的错误。就我而言,是艺术家姓名 u'Mø' 导致了问题。因此,这里有一个重现该问题的 1 行代码:

>>> str(u'Mø')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf8' in position 0: ordinal not in range(128)

您的错误明确地选出了字符u'\xe9':

>>> str(u'\xe9')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 0: ordinal not in range(128)

同样的问题,只是不同的性格。字符是Latin small letter e with acute 。 Python 尝试使用默认编码“ascii”将 Unicode 字符串转换为 str,但“ascii”不知道代码点是什么。

I believe the issue is happening in the final piece of code, with the JSON dump.

是的,是:

>>> with open('tmp.json', 'w') as f:
... json.dump(u'\xe9', f, ensure_ascii=False)
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "/usr/lib/python2.7/json/__init__.py", line 190, in dump
fp.write(chunk)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 1: ordinal not in range(128)

从回溯中,您可以看到它实际上来自写入文件 (fp.write(chunk))。

file.write()string 写入文件,但 u'\xe9' 是一个 unicode 对象。错误消息:'ascii' codec can't encode character... 告诉我们 python 正在尝试对 unicode 对象进行编码,将其转换为 str 类型,这样它就可以将其写入文件。对 unicode 字符串调用编码使用 "default string encoding" ,定义为 here为“ascii”。

要修复此问题,不要让 python 使用默认编码:

>>> with open('tmp.json', 'w') as f:
... json.dump(u'\xe9'.encode('utf-8'), f, ensure_ascii=False)
...
# No error :)

在您的具体示例中,您可以通过更改以下内容来修复间歇性错误:

allSanFranciscoEvents.append(eventsJSON)

对此:

allSanFranciscoEvents.append(eventsJSON.encode('utf-8'))

这样,您就显式地使用“utf-8”编解码器将 Unicode 字符串转换为 str,这样 python 就不会尝试应用默认值写入文件时编码为“ascii”。

关于python - BeautifulSoup webscraper 中的 UnicodeEncodeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54499230/

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