python - 如何取消抓取 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())
我的输出:
- 虚拟文本
- 不需要的文本
- 没有文字
- Lorem ipsum dolor sit amet
- sed 做 eiusmod 临时事件
- consectetur adipiscing 精英
- ut labore et dolore magna
我需要什么:
- Lorem ipsum dolor sit amet
- sed 做 eiusmod 临时事件
- consectetur adipiscing 精英
- ut labore et dolore magna
由于我是 SOF 的新手,如果我违反了任何准则,请在评论中提及。
解决方案
您应该将 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 元素。
推荐阅读
- python - 如何从图像中的边缘到连接的组件
- python - 尝试使用 Dask 读取 Redshift 外部表时出现“sqlalchemy.exc.NoSuchTableError”
- sql - 在 SQL Server 中使用 Merge 语句
- r - R中的虚拟变量,结果全部为0
- ios - 字符串:字符串?数组而不是字符串:字符串数组在 SwiftUI 视图中中断 ForEach?
- arrays - 如何在 Swift 中将 Nil 对象添加到对象数组中
- java - 如何使用预签名 URL 限制 AWS S3 存储桶中对象的上传大小?
- scala - 字节数组到Json对象的高效解析
- java - 在 Java 中将 HTML 字符串转换为 PDF 字节数组
- wordpress - 是否可以将搜索结果用作 $args 的一部分?