python - 我有 4 个嵌套的 div 标签,当我使用 find_all 打印文本时,它打印文本 4 次

标签 python html beautifulsoup

我正在从一个包含大量 div 标签的 html 文件中提取文本。但是,在某些地方有 4 个嵌套的 div 标签,当我打印文本时,它会打印 4 次。

<div>
    <div id="PGBRK" style="TEXT-INDENT: 0pt; WIDTH: 100%; MARGIN-LEFT: 0pt; MARGIN-RIGHT: 0pt">
        <div id="PN" style="PAGE-BREAK-AFTER: always; WIDTH: 100%">
            <div style="TEXT-ALIGN: center; WIDTH: 100%"><font style="DISPLAY: inline; FONT-FAMILY: Times New Roman; FONT-SIZE: 10pt">27</font></div> 
        </div>
    </div>
</div>

例如,如果我这样做:

for item in page_soup.find_all('div'):
    if "27" in item.text:
            print(item)

它打印了四次数字 27,因此弄乱了整个文本。 如何让我的代码只打印一次嵌套文本?

编辑 1: 这适用于这部分代码。但正如我所说,这只在某些地方是正确的。例如,当我这样做时:

for item in page_soup.find_all('div', recursive = False):
    print(item)

它不打印任何东西。作为引用,this是我要抓取的文档。

编辑 2: 从给定的 html 中,我试图提取“ITEM 1A. RISK FACTORS”部分。

should_print = False

for item in page_soup.find_all('div'):
    if "ITEM 1A." in item.text:
        should_print = True
    elif "ITEM 1B." in item.text:
        break
    if should_print:
        print(item)

所以我从第 1A 项开始打印所有内容。直到找到 ITEM 1B。 这里有些地方有嵌套的 div 标签,这段代码会打印多次。

如果我这样做,recursive = False,它不会打印任何东西。

最佳答案

这里有一个选项

import bs4, re

html = '''<div>
<div id="PGBRK" style="TEXT-INDENT: 0pt; WIDTH: 100%; MARGIN-LEFT: 0pt; MARGIN-RIGHT: 0pt">

<div id="PN" style="PAGE-BREAK-AFTER: always; WIDTH: 100%">

<div style="TEXT-ALIGN: center; WIDTH: 100%"><font style="DISPLAY: inline; FONT-FAMILY: Times New Roman; FONT-SIZE: 10pt">27</font></div>

</div>
</div>
</div>
</div>'''

soup = bs4.BeautifulSoup(html,'html.parser')
elements = soup.find_all(text=re.compile('27'))
print(elements)

输出

[u'27']

关于python - 我有 4 个嵌套的 div 标签,当我使用 find_all 打印文本时,它打印文本 4 次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56516915/

相关文章:

python - urrlib2 请求 https 站点 - 出现 400 错误

javascript - 将图像悬停效果和功能应用于 PSD 图像

python - 在 Python 的 span 标签中查找多个属性

python - 使用 beautifulsoup 进行网页抓取 : separating values

python - 换行符阻止 BeautifulSoup 提取数据

python - 为 Python 项目构建 Dockerfile 时出错

python - Neo4j 与 Python 驱动程序 : number of nodes created is far less than expected?

python - Matplotlib 绘制多条线不起作用

javascript - 使用javascript将td宽度更改为百分比

javascript - jquery 加载/卸载内容