我在test.py中有以下BeautifulSoup代码。
#!/usr/bin/env python
# vim: set noexpandtab tabstop=2 shiftwidth=2 softtabstop=-1:
from bs4 import BeautifulSoup
import sys
soup = BeautifulSoup(sys.stdin.read(), 'html.parser', from_encoding='utf-8')
import re
from pprint import pprint
pprint(soup.find('div', text=re.compile(r'Scientific')))下面是两个html文件:
test1.html
<div class="heading4">Scientific/Research Contact(s)</div>test2.html
<div class="heading4"><a name="_Scientific/Research_Contact(s)"></a>Scientific/Research Contact(s)</div>这是搜索结果。
$ ./test.py < test1.html
<div class="heading4">Scientific/Research Contact(s)</div>
$ ./test.py < test2.html
None有人知道为什么找不到第二个吗?
发布于 2016-01-03 10:59:55
在按名称和文本搜索元素时,BeautifulSoup会检查元素的.string以匹配所需的文本。这种令人困惑的行为实际上在documentation中有所涉及
如果您同时传递string和特定于标记的参数之一find*方法,则Beautiful Soup将搜索与特定于标记的条件匹配且其
Tag.string与字符串值匹配的标记。它不会找到字符串本身。以前,Beautiful Soup忽略特定于标签的参数,并查找字符串。
在第二种情况下,div元素的.string是None -这就是为什么您得不到任何结果的原因。相反,直接查找文本节点:
soup.find(text=re.compile(r"Scientific"))而且,如果您需要实际的父元素,可以从.parent获取它
soup.find(text=re.compile(r"Scientific")).parenthttps://stackoverflow.com/questions/34572857
复制相似问题