使用python将某些网站的HTML保存在txt文件中

时间:2014-06-19 01:05:17

标签: python html parsing python-3.x urllib

我需要在txt文件中保存任何网站的HTML代码,这是一个非常简单的练习,但我对此有疑问,因为有一个函数可以做到这一点:

import urllib.request

def get_html(url):
    f=open('htmlcode.txt','w')
    page=urllib.request.urlopen(url)
    pagetext=page.read() ## Save the html and later save in the file
    f.write(pagetext)
    f.close()

但这不起作用。

2 个答案:

答案 0 :(得分:11)

最简单的方法是使用urlretrieve

import urllib

urllib.urlretrieve("http://www.example.com/test.html", "test.txt")

对于Python 3.x,代码如下:

import urllib.request    
urllib.request.urlretrieve("http://www.example.com/test.html", "test.txt")

答案 1 :(得分:2)

我使用Python 3
pip install requests-安装requests库后,您可以将网页保存为txt文件。

import requests

url = "https://stackoverflow.com/questions/24297257/save-html-of-some-website-in-a-txt-file-with-python"

r = requests.get(url)
with open('file.txt', 'w') as file:
    file.write(r.text)