我有一个小脚本可以从 .html 文件中提取一些文本。
f = open(local_file,"r")
for line in f:
searchphrase = '<span class="position'
if searchphrase in line:
print("found it\n")
这对我来说很好(稍后将导入错误处理),我的问题是我要提取的文本位于搜索短语之后的 2 行之后。如何在 .html 文件中向下移动 2 行?
最佳答案
您可以通过调用 next()
将 f
(这是一个可迭代对象)推进两行在上面两次:
with open(local_file,"r") as f
for line in f:
searchphrase = '<span class="position'
if searchphrase in line:
print("found it\n")
next(f) # skip 1 line
return next(f) # and return the line after that.
但是,如果您尝试解析 HTML,请考虑使用 HTML 解析器代替。使用 BeautifulSoup ,例如。
关于 python 3.x : move to next line,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15656817/