如何用Python将HTML动态写入文件

2024-03-28 05:50:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下代码:

for item in soup.select('.profile-detail'):
    f= open('htmlfile.html', 'w')
    f.write(item)
    f.close()

我想把项目写进“htmlfile.html文件“但它给了我一个错误:

TypeError: write() argument must be str, not Tag


Tags: 文件项目代码inforclosehtmlopen
2条回答

我从你的截图中的soup中得知,你正在使用BeautifulSoup来提取带有“profile detail”类的元素。鉴于此,您的代码有两个问题:

  1. select()函数返回的列表中的值item是标记类的一个实例,file对象的write方法需要一个字符串。作为@PRMoureu wrote,您可以将标记实例强制转换为字符串,它将返回它表示的原始HTML字符串,方法是将文件写入行替换为以下内容:

    f.write(str(item))
    
  2. 打开的文件在循环中以write(“w”)模式打开。这意味着,对于循环的每次迭代,文件都将被覆盖,如果您试图收集查询返回的所有元素,则只能得到最后一个元素。如果要在文件中包含所有这些文件,以下是解决此问题的替代方法:

    ^{pr2}$

    但这并不太好,因为在每次迭代中都不需要打开和关闭文件。我们可以为所有写操作打开文件:

    # Open and close file just once
    f = open('htmlfile.html', 'w')            # Okay to open in write mode now
    for item in soup.select('.profile-detail'):
        f.write(item)
        f.write('\n') # In case you're expecting each on a new line
    f.close()
    

    或者,我个人的最爱是,做同样的事情,但是要考虑上下文,这样你就不会担心忘记f.close()或者不小心给了它错误的缩进或者以后的事情:

    # With contexts
    with open('htmlfile.html', 'w') as f:
        for item in soup.select('.profile-detail'):
             f.write(item)
             f.write('\n') # In case you're expecting each on a new line
    # File is auto-magically closed by the time you get here
    

只需使用str()获取整个标记内容:

with open('htmlfile.html', 'w') as f:
    for item in soup.select('.profile-detail'):
        f.write(str(item) + '\n') # thanks jeteon :p, it's cleaner

相关问题 更多 >