我开始学习 Python,我决定编写一个简单的爬虫程序。我遇到的一个问题是无法将 NavigableString 转换为常规字符串。
使用 BeautifulSoup4 和 Python 3.5.1。我应该硬着头皮去使用早期版本的 Python 和 BeautifulSoup 吗?或者有没有一种方法可以编写自己的函数以将 NavigableString 转换为常规 unicode 字符串?
for tag in soup.find_all("span"):
for child in tag.children:
if "name" in tag.string: #triggers error, can't compare string to NavigableString/bytes
return child
#things i've tried:
#if "name" in str(tag.string)
#if "name" in unicode(tag.string) #not in 3.5?
#if "name" in strring(tag.string, "utf-8")
#tried regex, didn't work. Again, doesn't like NavigableSTring type.
#... bunch of other stuff too!
原文由 Saustin 发布,翻译遵循 CC BY-SA 4.0 许可协议
我在应该编码的时候尝试解码: