python - 如何使用 BeautifulSoup 逐行读取数据?
问题描述
我有以下代码,它为我提供了 Example.html 文件中的数据。但我必须逐行读取数据
html_doc = open("Example.html","r")
soup = BeautifulSoup(html_doc, 'html.parser')
print(soup.get_text())
解决方案
您可以使用 splitlines() 方法轻松地逐行读取数据。
对于您的情况,您可以使用:
html_doc = open("Example.html","r")
soup = BeautifulSoup(html_doc, 'html.parser')
output = soup.get_text()
for row in output.splitlines():
# Do whatever you want
编辑:对于您在 if 条件后读取 20 行的请求,您可以枚举splitlines()方法并读取接下来的 20 行。然后,使用break语句退出 for 循环。
for idx, row in enumerate(output.splitlines()):
if row == "ADD.c":
twenty_line = idx + 20
try:
if idx < twenty_line:
print(row + "\n")
else:
break
except NameError as e:
print(e)
推荐阅读
- mysql - Grafana:将文本框(模板变量)转换为整数
- java - Java Maven 在 Eclipse 中工作,但在 OpenShift 中不工作
- java - 如何从流中删除数字和空格?
- javascript - 通过单击删除照片
- asp.net-core - 如何重定向到自定义错误处理程序页面
- c# - AspNet Core - 控制器级别的输入/输出 JSON 序列化设置
- gtk3 - Python:更改 GtkTreeview 中的选择颜色
- android - IONIC 3 - 提高图像选择器性能和排序选项
- libgdx - libgdx 是否支持 webp 格式(image.webp)?我想减小应用程序的大小
- c++ - 近指针声明中缺少分号 - microsoft visual c++ 2015/2017/2019