python 3.x : move to next line

标签 python python-3.x

我有一个小脚本可以从 .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/

相关文章:

python-3.x - 无法捕获TweepError异常

Python - 字典比较

python-3.x - 尽管之前的实现工作正常,但可整除计算器仍失败

python - 用总和替换 NumPy 数组和单个数字字典中的值

python - 将字符串拆分为整数时出现类型错误

python - 使用 ReportLab.platypus 渲染后是否可以获得 Flowable 的坐标位置?

Python 3 - 将列表中的数字乘以 2

python - 如何计算 pandas 行之间的条件百分比变化?

python - 复制 xpath 未提供正确的 xpath?

python - 如何在 VS Code 环境中修复 "Exception has occurred: SSLError HTTPSConnectionPool"