Skip to main content
 首页 » 编程设计

Python 'ascii' 编解码器无法使用 request.get 对字符进行编码

2024年10月17日16yxwkf

我有一个 Python 程序,它从站点抓取数据并返回一个 json。被抓取的站点具有元标记字符集 = ISO-8859-1。这是源代码:

url = 'https://www.example.com' 
source_code = requests.get(url) 
plain_text = source_code.text 

之后,我使用 Beautiful Soup 获取信息,然后创建一个 json。问题是,一些符号,即 € 符号显示为\u0080 或\x80(在 python 中),所以我不能在 php 中使用或解码它们。所以我尝试了 plain_text.decode('ISO-8859-1) 和 plain_text.decode('cp1252') 所以我可以在之后将它们编码为 utf-8 但每次我收到错误消息:'ascii' 编解码器无法对位置 8496 中的字符 u'\xf6' 进行编码:序号不在范围 (128) 内。

编辑

@ChrisKoston 建议使用 .content 而不是 .text 后的新代码

url = 'https://www.example.com' 
source_code = requests.get(url) 
plain_text = source_code.content 
the_sourcecode = plain_text.decode('cp1252').encode('UTF-8') 
soup = BeautifulSoup(the_sourcecode, 'html.parser') 

现在可以编码和解码了,但仍然是字符问题。

EDIT2

解决方法是设置.content.decode('cp1252')

url = 'https://www.example.com' 
source_code = requests.get(url) 
plain_text = source_code.content.decode('cp1252') 
soup = BeautifulSoup(plain_text, 'html.parser') 

特别感谢 Tomalak 提供的解决方案

请您参考如下方法:

您实际上必须将 decode() 的结果存储在某处,因为它不会修改原始变量。

另一件事:

  • decode() 将字节列表转换为字符串。
  • encode() 做相反的事情,它将一个字符串变成一个字节列表

BeautifulSoup 对字符串很满意;您根本不需要使用 encode()。

import requests 
from bs4 import BeautifulSoup 
 
url = 'https://www.example.com' 
response = requests.get(url) 
html = response.content.decode('cp1252') 
soup = BeautifulSoup(html, 'html.parser') 

提示:要使用 HTML,您可能需要查看 pyquery而不是 BeautifulSoup。