我是 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/