【问题标题】:BeautifulSoup output encoding: how to combine soup.p.encode("utf-8") with soup.select('a') & .getText()BeautifulSoup 输出编码:如何将soup.p.encode("utf-8") 与soup.select('a') & .getText() 结合起来
【发布时间】:2016-12-02 14:18:08
【问题描述】:

关于 Python BeautifulSoup 输出编码(使用 Python 3.4.4):

如何将soup.p.encode("utf-8") 与soup.select('a') & .getText() 结合起来?

即我可以做两者之一,但不知道如何做... -> 我想使用 soup.p.encode("utf-8") 因为例如否则,“Aloë”将在我的输出中转换为“aloë”。

但我也想使用汤对象(类型:)通过“soup.select('a')和“.getText()”选择href对象。如果我做soup.p.encode(“ utf-8") 首先这是不可能的,因为我得到“AttributeError: 'bytes' object has no attribute 'select'。

但似乎一旦我将汤对象转换为一个列表,然后是一个字符串,是否为时已晚,无法恢复 UTF-8 字符?例如。 text = text.decode('utf-8') 不起作用。我真的可以使用一些建议!

仅供参考我的代码:

import requests, bs4

res = requests.get(url)
try:
    res.raise_for_status()
except Exception as exc:
    print('There was a problem: %s' % (exc))

soup = bs4.BeautifulSoup(res.text,"html.parser", from_encoding="UTF-8")
#soup = soup.encode("utf-8")
#type: <class 'bs4.BeautifulSoup'>
#print(soup.original_encoding) -> None...
aElems = soup.select('a')
#type: <class 'list'>
lengthElems = len(aElems)

for i in range (0, lengthElems):
    text = aElems[i].getText()
    #text = text.decode('utf-8')
    link = aElems[i].get('href')

【问题讨论】:

  • FYI 作为一种解决方法我现在已经在我的 Excel 输出文件中搜索并替换了以下代码 - 字符组合:á á âl â ç ,c é é è è ë ë î î iÌ ï ñ ñ ò ò ó ó ö ö ü ü ú ú ï ï â ' ⦠...

标签: python encoding utf-8 beautifulsoup


【解决方案1】:

您可以在脚本中将系统默认编码设置为 UTF-8。

在你想要的文件顶部:

import sys

if __name__ == "__main__":
    reload(sys)
    sys.setdefaultencoding("utf-8")

【讨论】:

  • 感谢您的快速答复。抱歉,我忘了提及我使用的是 Python 版本 3.4.4 [MSC v.1600 64 位 (AMD64)]。我认为 utf-8 已经是默认值了?我想这也是我得到“未定义名称'reload'”的原因。所以我已经导入了 importlib 来使用它进行重新加载,但后来我得到“'module' object has no attribute 'setdefaultencoding'”...
猜你喜欢
  • 2020-02-03
  • 2016-07-05
  • 1970-01-01
  • 1970-01-01
  • 2020-12-31
  • 2016-11-28
  • 2014-01-27
  • 1970-01-01
  • 2019-09-03
相关资源
最近更新 更多