How to read HTML line by line

This question already has an answer here:

  • In Python, how do I read a file line-by-line into a list? 35 answers

  • You can use f.readlines() instead of f.read() . This function returns a list of all the lines in the file.

    with open("/home/tony/Downloads/page1/test.html", "r") as f:
        for line in f.readlines():
            print(line)
    

    Alternatively you could use list(f) .

    f = open("/home/tony/Downloads/page1/test.html", "r")
    f_lines = list(f)
    for line in f_lines:
        print(line)
    

    Source: https://docs.python.org/3.5/tutorial/inputoutput.html


    f.read() will attempt to read and yield each character until an EOF is met. What you want is the f.readlines() method:

    with open("/home/tony/Downloads/page1/test.html", "r") as f:
        for line in f.readlines():
            print(line) # The newline is included in line
    
    链接地址: http://www.djcxy.com/p/42344.html

    上一篇: 逐行读取TXT文件

    下一篇: 如何逐行阅读HTML