代码之家  ›  专栏  ›  技术社区  ›  ep84

如何在Python中编码/解码这个美丽的字符串,以便输出非标准拉丁字符?

  •  3
  • ep84  · 技术社区  · 7 年前

    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 ,但运气不好。感谢蛇怪提供的信息。

    2 回复  |  直到 7 年前
        1
  •  2
  •   snakecharmerb    7 年前

    打印时不需要对值进行编码-打印功能将自动处理此问题。现在,您正在打印组成编码值的字节的表示形式,而不仅仅是字符串本身。

    >>> s = 'hǎo'
    >>> print(s)
    hǎo
    
    >>> print(s.encode('utf-8'))
    b'h\xc7\x8eo'
    
        2
  •  1
  •   nandu kk    7 年前

    在调用BeautifulSoup时使用encode,而不是在调用之后。

    soup=BeautifulSoup(driver.page_source.encode('utf-8'), '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)
    
    推荐文章