我有一个复杂的HTML文档,其中嵌套了<div>
标签,例如:
<html>
<body>
<div id="one">
<p>1. Get this div!</p>
</div>
<div id="two">
<div>
<div id="three">
<p>2. Get this div!</p>
</div>
</div>
<div id="four">
<p>3. Get this div!</p>
</div>
</div>
</body>
</html>
我正在尝试使用以下代码:
soup = BeautifulSoup(html, 'html.parser')
div_list = soup.find_all('div')
但是,上面的代码仅获得最高级的div,这意味着它将仅返回ID为“ one”和“ two”的div。 但是,我想使用BeautifulSoup返回ID为“一个”,“三个”和“四个”的div列表。我该怎么做?
答案 0 :(得分:1)
最简单的方法是创建具有所需ID的列表,然后使用re.compile
:
from bs4 import BeautifulSoup as soup
import re
ids = ['one', 'three', 'four']
results = soup(content, 'html.parser').find_all('div', {'id':re.compile('|'.join(ids))})
for i in results:
print(i)
print('-'*20)
输出:
<div id="one">
<p>1. Get this div!</p>
</div>
--------------------
<div id="three">
<p>2. Get this div!</p>
</div>
--------------------
<div id="four">
<p>3. Get this div!</p>
</div>
--------------------
但是,在不使用搜索列表的情况下,可以使用递归:
def get_ids(_d):
if not any(getattr(i, '__dict__', {}).get('name') == 'div' for i in _d.__dict__['contents']):
return _d
_r = [get_ids(i) for i in _d.__dict__['contents'] if getattr(i, '__dict__', {}).get('name') == 'div']
return None if not _r else _r[0]
final_results = []
for i in [get_ids(i) for i in soup(content, 'html.parser').find_all('div')]:
if i not in s:
s.append(i)
print(final_results)
输出:
[<div id="one"><p>1. Get this div!</p></div>, <div id="three"><p>2. Get this div!</p></div>, <div id="four"><p>3. Get this div!</p></div>]
答案 1 :(得分:0)
您可以直接检查找到的任何部门内部是否有更多部门:
[d for d in soup.findAll('div') if not d.find('div')]
#[<div id="one"><p>1. Get this div!</p></div>,
# <div id="three"><p>2. Get this div!</p></div>,
# <div id="four"><p>3. Get this div!</p></div>]