簡體   English   中英

用python將某個網站的HTML保存在一個txt文件中

[英]Save HTML of some website in a txt file with python

我需要將任何網站的 HTML 代碼保存在一個 txt 文件中,這是一個非常簡單的練習,但我對此表示懷疑,因為有一個功能可以做到這一點:

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()

但這不起作用。

最簡單的方法是使用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")

我使用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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM