Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/339.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python UnicodeEncodeError:&x27;ascii';编解码器可以';t编码字符'\u2159';位置32:序号不在范围内(128)_Python_Python 3.x_Url_Beautifulsoup_Python Unicode - Fatal编程技术网

Python UnicodeEncodeError:&x27;ascii';编解码器可以';t编码字符'\u2159';位置32:序号不在范围内(128)

Python UnicodeEncodeError:&x27;ascii';编解码器可以';t编码字符'\u2159';位置32:序号不在范围内(128),python,python-3.x,url,beautifulsoup,python-unicode,Python,Python 3.x,Url,Beautifulsoup,Python Unicode,我正在使用python3和beautifulsoup来刮取网站,但我遇到了这个错误。我试图用其他答案中给出的解决方案来解决这个问题,但没有一个解决了我的问题 #-*-编码:utf-8-*- 导入操作系统 导入区域设置 os.environ[“PYTHONIOENCODING”]=“utf-8” myLocale=locale.setlocale(category=locale.LC_ALL,locale=“en_GB.UTF-8”) 从urllib.request导入urlopen 从bs4导入

我正在使用python3和beautifulsoup来刮取网站,但我遇到了这个错误。我试图用其他答案中给出的解决方案来解决这个问题,但没有一个解决了我的问题

#-*-编码:utf-8-*-
导入操作系统
导入区域设置
os.environ[“PYTHONIOENCODING”]=“utf-8”
myLocale=locale.setlocale(category=locale.LC_ALL,locale=“en_GB.UTF-8”)
从urllib.request导入urlopen
从bs4导入BeautifulSoup
进口稀土
作为pd进口熊猫
def getrank(动物):
html=urlopen(animeurl)
bslink=BeautifulSoup(html.read(),'html.parser')
rank=bslink.find('span',{'class':'numbers ranked'}).get_text().replace('ranked#','')
def spring19():
html=urlopen('https://...')
bs=BeautifulSoup(html.read(),'html.parser')
链接=[]
对于bs.find_all('a',{'class':'link title'})中的x:
link.append(x.get(“href”))
ranklist=[]
对于链接中的x:
x、 编码(encoding='UTF-8',errors='ignore')
ranklist.append(getrank(x))
回程表
spring19()
错误消息是: UnicodeEncodeError:“ascii”编解码器无法对位置32中的字符“\u2159”进行编码:序号不在范围内(128)

出现此错误的原因是,我刮取的URL中有一些符号。但我仍然不知道该如何修复它


非常感谢

通过以下解决方案解决了此问题:

代码修改如下:

ranklist=[]
对于链接中的x:
x=引号(x,安全='/:?=&')
ranklist.append(getrank(x))

您是否尝试过其他类型的编码?例如Windows-1252?您应该能够从HTML本身(在头PAR,字符集元元素)中获得用于网页的编码,或者,可能更好地,从服务器提供的标头(漂亮的汤不会有任何知识;一旦下载文档,它就会丢失)。。请指出脚本中发生错误的确切位置。您从未将
x.encode(encoding='UTF-8',errors='ignore')
的结果分配给任何内容
x
保留了以前的状态,因为编码的结果被丢弃了。非常感谢您的帮助!网站使用的编码实际上是utf-8。但是我发现这个错误的原因是有一些符号,比如☆ 在我废弃的URL中,我仍在努力解决这个问题。