如何获取html文件的源代码并放入字符串

时间:2015-10-29 14:38:10

标签: python html

是否可以在变量中放入HTML文件的源代码?

我的意思是,如果我有test.html,那么如何获取此html文件的源代码并将其放在字符串上呢?

1 个答案:

答案 0 :(得分:3)

只需打开文件并阅读:

f = open('test.html', 'r')
html_string = f.read()
f.close()

with open('test.html', 'r') as f:  # with can auto close the file like f.close() does
    html_string = f.read()