我正在用 Beautiful Soup 抓取一个页面,输出包含显示为十六进制的非标准拉丁字符。
我正在抓取 https://www.archchinese.com .它包含使用非标准拉丁字符(例如ǎ、ā)的拼音词。我一直在尝试遍历一系列包含拼音的链接,使用 BeautifulSoup .string 函数以及 utf-8 编码来输出这些单词。这个词在非标准字符的地方以十六进制出现。 “hǎo”字出来就是“h\xc7\x8eo”。我确定我在编码时做错了什么,但我不知道要修复什么。我首先尝试使用 utf-8 解码,但出现该元素没有解码功能的错误。尝试在不编码的情况下打印字符串会给我一个关于字符未定义的错误,我认为这是因为它们需要先编码为某种东西。
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from bs4 import BeautifulSoup
import re
url = "https://www.archchinese.com/"
driver = webdriver.Chrome() #Set selenium up for opening page with Chrome.
driver.implicitly_wait(30)
driver.get(url)
driver.find_element_by_id('dictSearch').send_keys('好') # This character is hǎo.
python_button = driver.find_element_by_id('dictSearchBtn')
python_button.click() # Look for submit button and click it.
soup=BeautifulSoup(driver.page_source, 'lxml')
div = soup.find(id='charDef') # Find div with the target links.
for a in div.find_all('a', attrs={'class': 'arch-pinyin-font'}):
print (a.string.encode('utf-8')) # Loop through all links with pinyin and attempt to encode.
实际结果: b'h\xc7\x8eo' b'h\xc3\xa0o'
预期结果: hǎo 好
编辑:问题似乎与 Windows 中的 UnicodeEncodeError
有关。我尝试安装 win-unicode-console
,但没有成功。感谢 snakecharmerb 提供的信息。
最佳答案
打印时不需要对值进行编码 - 打印函数会自动处理。现在,您正在打印构成编码值的字节表示,而不仅仅是字符串本身。
>>> s = 'hǎo'
>>> print(s)
hǎo
>>> print(s.encode('utf-8'))
b'h\xc7\x8eo'
关于python - 如何在 Python 中编码/解码这个 BeautifulSoup 字符串,以便输出非标准的拉丁字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53898204/