Python 3.x:转到下一行

Sai*_*ore 2 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")
Run Code Online (Sandbox Code Playgroud)

这对我来说很好(错误处理将在以后导入),我的问题是我要提取的文本在搜索短语之后跟随2行.如何在.html文件中向下移动2行?

Mar*_*ers 9

您可以f通过两次调用来提前(这是一个可迭代的)两行next():

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.
Run Code Online (Sandbox Code Playgroud)

但是,如果你试图解析HTML,请考虑使用HTML解析器来代替.例如,使用BeautifulSoup.