關於Python BeautifulSoup輸出編碼(使用Python 3.4.4):BeautifulSoup輸出編碼:如何結合soup.p.encode(「utf-8」)與soup.select('a')&.getText()
如何結合soup.p.encode(「utf-8」)與soup.select('a')& .getText()?
I.e.我可以做兩個之一,但不知道如何做兩個... - >我想使用soup.p.encode(「utf-8」),因爲例如,在我的輸出中,「Aloë」會另外轉換爲「alo?」。
但我也想使用湯對象(類型:)通過「soup.select('a')和」.getText()「來選擇href對象。如果我做了soup.p.encode 「utf-8」)首先這是不可能的,因爲我得到「AttributeError:'字節'對象沒有'select'屬性。
但是,似乎一旦我將湯對象轉換爲一個列表,然後是一個字符串,那麼獲取UTF-8字符爲時已晚?例如。 text = text.decode('utf-8')不起作用。我真的可以請一些建議!
FYI我的代碼:
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 A §,C éé A E ëë A®î II I A±ñ A²ò A 3ó öö 那張ü úU Ãïï à Ä... – Wouter