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

标签 python json encoding utf-8 ascii

我有一个 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/

相关文章:

python:如何从代码对象中获取源代码?

jQuery 克隆问题

encoding - 如何在 elixir 中将二进制转换为 base10(十进制)整数

python - 在python中将任何编码转换为utf8?

python - Flask_mysql 给出错误 "ExtDeprecationWarning: Detected extension named flaskext.mysql please rename it to flask_mysql."

python - 制作networkx图,其中边缘仅显示编辑的数值,而不显示字段名称

python - 使用python将JSON导入mysql

java - Google 方向 JSON 到 POJO ( jackson )

IOS/objective-C : How to Access JSON within parentheses

ruby - 非破坏性force_encoding?