首页 > 解决方案 > 如何取消抓取 div 中的前 x 个 p 标签并打印其余部分?

问题描述

过去几天我一直在学习 python。今天我带来了一个叫做网络抓取的主题。我正在尝试刮除第一个 3 p 标签之外的 div 内的所有 p 标签。由于 p 标签没有类或 id,我无法找到取消抓取它们的方法

我的代码:

from bs4 import BeautifulSoup

data = '''<div class="one">
    <p style="color:red">Dummy Text</p>
    <p style="color:red">Unwanted Text</p>
    <p style="color:red">No Text</p>
    <p style="color:red">Lorem ipsum dolor sit amet</p>
    <p style="color:red">sed do eiusmod tempor incididunt</p>
    <p style="color:red">consectetur adipiscing elit</p>
    <p style="color:red">ut labore et dolore magna</p>
</div>'''

text = BeautifulSoup(data, 'html.parser')
for result in text.find_all('p'):
    print(result.get_text())

我的输出:

我需要什么:

由于我是 SOF 的新手,如果我违反了任何准则,请在评论中提及。

标签: pythonweb-scraping

解决方案


您应该将 div 字符串添加到数组中以存储它们。然后,您应该删除数组的前三个元素。这可以这样做:

text = BeautifulSoup(data, 'html.parser')
p_list = []
for result in text.find_all('p'):
    p_list.append(result.get_text())
# this selects all elements from the list after the third
p_list = p_list[3:]

这将为您提供一个列表,其中包含除前三个之外的所有 p 元素。


推荐阅读