BeautifulSoup:无法将 NavigableString 转换为字符串

新手上路,请多包涵

我开始学习 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 许可协议

阅读 676
2 个回答

我在应该编码的时候尝试解码:

 str(child.encode('utf-8'))

原文由 Saustin 发布,翻译遵循 CC BY-SA 3.0 许可协议

对于 Python 3…

…答案仅仅是 str(tag.string)

其他答案将失败。

unicode() 不是 Python 3 的内置函数。

tag.string.encode('utf-8') 会将字符串转换为您不想要的字节字符串..

原文由 Konchog 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进