python - BeautifulSoup - 在看似简单的情况下解析问题

标签 python python-2.7 beautifulsoup

我是 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 变量进行了诊断,但是(正如预期的那样)这似乎不是一个解析问题,因为所有内容都与它最初在字符串上的情况差不多。

最佳答案

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

If a tag contains more than one thing, then it’s not clear what .string should refer to, so .string is defined to be None

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

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

exampleSoup.a.get_text()

关于python - BeautifulSoup - 在看似简单的情况下解析问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41664083/

相关文章:

python - pandas 替换行和列子集的空值

Python Selenium Firefox 脚本在重新启动驱动程序实例后崩溃

python - 如何向用户输出力量?

Python - 检查列表中的所有字母是否与字符串中的字母匹配?

python - Python2.7中在带有空格和逗号的字符串后创建一个新行

Django:访问子模板中的循环变量

html - 用 beautifulsoup 选择元素

python - BeautifulSoup 使用 python 删除除白名单中的所有 html 标签,例如 "img"和 "a"标签

Python - 逐行读取 BeautifulSoup 片段? (或其他抓取我想要的数据的方法)

python - 在 Cerberus 中,您可以使用类型为 'valueschema' 的 'dict' 吗?