我正在尝试获取 HTML 文档中包含以下文本模式的元素:#\S{11}
<h2> this is cool #12345678901 </h2>
因此,前面的内容将通过使用以下方式进行匹配:
soup('h2',text=re.compile(r' #\S{11}'))
结果会是这样的:
[u'blahblah #223409823523', u'thisisinteresting #293845023984']
我能够获得所有匹配的文本(参见上面的行)。但我希望文本的父元素匹配,因此我可以将其用作遍历文档树的起点。在这种情况下,我希望返回所有 h2 元素,而不是文本匹配。
Ideas?
from BeautifulSoup import BeautifulSoup
import re
html_text = """
<h2>this is cool #12345678901</h2>
<h2>this is nothing</h2>
<h1>foo #126666678901</h1>
<h2>this is interesting #126666678901</h2>
<h2>this is blah #124445678901</h2>
"""
soup = BeautifulSoup(html_text)
for elem in soup(text=re.compile(r' #\S{11}')):
print elem.parent
Prints:
<h2>this is cool #12345678901</h2>
<h2>this is interesting #126666678901</h2>
<h2>this is blah #124445678901</h2>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)