https://www.archchinese.com
. 它包含使用非标准拉丁字符(例如)的拼音单词。我一直在尝试通过一系列包含拼音的链接进行循环,使用BeautifulSoup.string函数和utf-8编码来输出这些单词。这个词在非标准字符的地方用十六进制出现。“ho”一词的意思是“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'
预期成果:
圣约翰
呵
编辑:问题似乎与
UnicodeEncodeError
在窗户里。我已经试着安装了
win-unicode-console
,但运气不好。感谢蛇怪提供的信息。