CS_*_*oob 6 python unicode ascii beautifulsoup web-scraping
我正在学习Python中的美丽汤.
我试图解析一个包含书籍列表的简单网页.
例如
<a href="https://www.nostarch.com/carhacking">The Car Hacker’s Handbook</a>
Run Code Online (Sandbox Code Playgroud)
我使用下面的代码.
import requests, bs4
res = requests.get('http://nostarch.com')
res.raise_for_status()
nSoup = bs4.BeautifulSoup(res.text,"html.parser")
elems = nSoup.select('.product-body a')
#elems[0] gives
<a href="https://www.nostarch.com/carhacking">The Car Hacker\u2019s Handbook</a>
Run Code Online (Sandbox Code Playgroud)
和
#elems[0].getText() gives
u'The Car Hacker\u2019s Handbook'
Run Code Online (Sandbox Code Playgroud)
但我想要的是正确的文字,
s = elems[0].getText()
print s
>>>The Car Hacker’s Handbook
Run Code Online (Sandbox Code Playgroud)
如何修改我的代码以便给出"The Car Hacker's Handbook"输出而不是"u'The Car Hacker\u2019s Handbook"?
请帮助.
您是否尝试过使用编码方法?
elems[0].getText().encode('utf-8')
Run Code Online (Sandbox Code Playgroud)
有关 unicode 和 python 的更多信息可以在https://docs.python.org/2/howto/unicode.html中找到
此外,要发现您的字符串是否确实是 utf-8 编码的,您可以使用chardet并运行以下命令:
>>> import chardet
>>> chardet.detect(elems[0].getText())
{'confidence': 0.5, 'encoding': 'utf-8'}
Run Code Online (Sandbox Code Playgroud)