【发布时间】: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