我有一个 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')
现在可以进行编码和解码,但仍然存在字符问题。
编辑2
解决办法是设置.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。
关于Python 'ascii' 编解码器无法使用 request.get 对字符进行编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40660333/