如何刮HTML div不是另一个div的孩子?



我有HTML文件。对于每个文件,我想一个接一个地抓取所有表,并且仍然有表的索引用于获取表前的标题和一些文本。

我使用soup.find_all('divs')来拉所有div,并基于结果构建我的应用程序。

当我尝试另一个格式略有不同的HTML文件时,如下所示:

<div style="margin-top:27.85pt;margin-bottom:21.86pt;margin-left:69.66pt;width:456pt;">
<div style="text-align:center; width:456pt; line-height:14pt;font-weight:bold;color:#33058D;font-size:12pt;">UNITED STATES<br/>SECURITIES AND EXCHANGE COMMISSION<br/>Washington, D.C. 20549<font style="font-weight:normal;color:#3D3935;font-family:Times New Roman, Times, serif ;letter-spacing:0.24pt;"> </font></div>
<div style="margin-top:12pt; text-align:center; width:456pt; line-height:14pt;font-weight:bold;color:#33058D;font-size:12pt;">SCHEDULE 14A<font style="font-weight:normal;"> </font></div>
<div style="margin-top:8pt; text-align:center; width:456pt; line-height:11pt;">Proxy Statement Pursuant to Section&#160;14(a) of <br/>the Securities Exchange Act of 1934<font style="font-family:Times New Roman, Times, serif ;letter-spacing:0.18pt;"> </font></div>
</div>

包含1个div(父div)和3个子div。soup.find_all('div')返回4项:1个父div和子div,每个子div在主div中。

我想让它只拉父div。

divs = []
while len(html) > 0:
soup = BeautifulSoup(html, 'lxml')
div = soup.find('div')
divs.append(div)
length = len(str(div))
html = html[:len(html)-length]

我试着创建这个代码,但它是非常非常低效的,尽管结果正是我想要的。花了很长时间才完成。

不确定我是否理解正确,但如果你唯一的问题是你不确定如何提取父div,你可以使用这个css选择器:"div: Not (div>div),

这基本上指定选择所有不是其他div的直接子div。用这个和从beautifulSoup中选择的汤一起使用,应该就能达到效果了。下面是代码:

from bs4 import BeautifulSoup
html = """
<div style="margin-top:27.85pt;margin-bottom:21.86pt;margin-left:69.66pt;width:456pt;">
<div style="text-align:center; width:456pt; line-height:14pt;font-weight:bold;color:#33058D;font-size:12pt;">UNITED STATES<br/>SECURITIES AND EXCHANGE COMMISSION<br/>Washington, D.C. 20549<font style="font-weight:normal;color:#3D3935;font-family:Times New Roman, Times, serif ;letter-spacing:0.24pt;"> </font></div>
<div style="margin-top:12pt; text-align:center; width:456pt; line-height:14pt;font-weight:bold;color:#33058D;font-size:12pt;">SCHEDULE 14A<font style="font-weight:normal;"> </font></div>
<div style="margin-top:8pt; text-align:center; width:456pt; line-height:11pt;">Proxy Statement Pursuant to Section&#160;14(a) of <br/>the Securities Exchange Act of 1934<font style="font-family:Times New Roman, Times, serif ;letter-spacing:0.18pt;"> </font></div>
</div>
"""
soup = BeautifulSoup(html, 'html.parser')
divs = soup.select('div:not(div > div)')

最新更新