首页 > 解决方案 > 如何保存网页的源代码

问题描述

您好,我想将网页的源代码保存到任何文本文件并将其保存在 C:\ 文件夹中。

我尝试使用以下代码获取网页的源代码:

html = driver.page_source
print(html)

如何将页面源代码保存到文本文件中的 C:\ 文件夹?

标签: pythonhtmlseleniumselenium-webdriver

解决方案


尝试这个:

import urllib.request
site = urllib.request.urlopen('http://somesite.com')
data = site.read()
file = open("C:\\file.txt","wb") #open file in binary mode
file.writelines(data)
file.close()

或这个

import urllib.request
def extractHTML(url):
    urllib.request.urlretrieve(url, 'C:\\file.txt')

在此处查看更多详细信息


推荐阅读