18910140161

Python-如何抓取不是另一个DIV的子类的HTML DIV?-堆栈溢出

顺晟科技

2022-10-18 12:26:57

174

我有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.

<代码>DIVS=[]而len(HTML)>;0:汤=美丽的汤(HTML,' lxml ')DIV=soup.find(' DIV ')DIV.append(DIV)长度=len(str(DIV))HTML=HTML[:len(HTML)-length]

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


顺晟科技:

我不确定我的理解是否正确,但如果您遇到的唯一问题是不确定如何只提取父DIV,则可以使用这个CSS选择器:";DIV:not(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]
  • TAG:
相关文章
我们已经准备好了,你呢?
2024我们与您携手共赢,为您的企业形象保驾护航