【问题标题】:BeautifulSoup - Parsing issue on a seemingly simple situationBeautifulSoup - 在看似简单的情况下解析问题
【发布时间】:2023-03-04 03:24:01
【问题描述】:

我是 BeautifulSoup 的新手,昨天刚刚创建了我的第一个脚本。这是一些没有得到我期望的结果的代码:

html = """<a href="http://www.example.com"><b>Text</b> and more text</a>"""
exampleSoup = BeautifulSoup(html, "html.parser")
print exampleSoup.a.string

我希望得到...

<b>Text</b> and more text

但我得到“无”。我在错误地假设什么?

我对 html 变量进行了诊断,但(正如预期的那样)这似乎不是解析问题,因为一切都与字符串上的原始内容差不多。

【问题讨论】:

    标签: python python-2.7 beautifulsoup


    【解决方案1】:

    .string 将返回None,如果一个元素有多个子元素

    如果一个标签包含多个东西,那么不清楚 .string 应该指什么,所以 .string 被定义为 None

    您的意思是使用str(exampleSoup.a) 来获取元素的HTML 表示。

    或者,如果您想获取包括孩子在内的完整文本,请使用.get_text()

    exampleSoup.a.get_text()
    

    【讨论】:

    • 谢谢亚历克斯!这个答案有帮助,我忘了回信让你知道。
    猜你喜欢
    • 2011-11-05
    • 2010-10-10
    • 2011-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-05
    • 1970-01-01
    相关资源
    最近更新 更多