2012-04-01 129 views
4

如何將網站的源代碼複製到Python 3中的文本文件中?將HTML源代碼保存到文件

編輯: 爲了澄清我的問題,這是我有:

import urllib.request 

def extractHTML(url): 
    f = open('temphtml.txt', 'w') 
    page = urllib.request.urlopen(url) 
    pagetext = page.read() 
    f.write(pagetext) 
    f.close() 

extractHTML('http:www.google.com') 

我得到以下錯誤的f.write()函數:

builtins.TypeError: must be str, not bytes 
+0

您是否試過在這裏尋找?:http://stackoverflow.com/questions/5512811/builtins-typeerror-must-be-str-not-bytes – Jack 2012-04-01 21:08:08

+0

令人驚訝的是,沒有一個答案(除了一個)實際上解決了這個問題..'pagetext'不是一個字符串..它實際上是字節。所以要將它轉換爲一個字符串,你需要使用'f.write(pagetext.decode('utf-8'))'這將把一個UTF-8編碼的字符串轉換爲文件。 – Brandon 2017-10-12 23:57:58

+0

@Brandon我嘗試了你所說的並且得到一個錯誤:UnicodeDecodeError:'utf-8'編解碼器無法解碼位置8482中的字節0xa0:無效的開始字節。我只是在沒有'str()'的情況下直接複製了我的答案,並將'f.write(pagetext.decode('utf-8'))'放在'f.write(pagetext)'的位置。任何想法爲什麼這不適合我。如果你使用的是Python 2,那麼可能是爲什麼 – Simon 2017-10-13 00:40:19

回答

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

未經測試,但應該管用。

編輯:更新了python3

+0

不*工作。 OP使用python 3. – DSM 2012-04-01 20:46:25

+0

糟糕,抱歉。 Python 3中有什麼問題?對於初學者, – Jack 2012-04-01 20:50:13

+0

urllib2不存在。我認爲你通常會使用urllib.request模塊(這就是urlopen現在所處的位置)。 – DSM 2012-04-01 20:51:52

0

probably you wanted to create something like that:

import urllib.request 

class ExtractHtml(): 

    def Page(self): 

     print("enter the web page name starting with 'http://': ") 
     url=input() 
     site=urllib.request.urlopen(url) 
     data=site.read() 
     file =open("D://python_projects/output.txt", "wb") 
     file.write(data) 
     file.close() 






w=ExtractHtml() 
w.Page() 
0

試試這個。

import urllib.request 
def extractHTML(url): 
    urllib.request.urlretrieve(url, 'temphtml.txt') 

這是比較容易的,但如果你仍然想這樣做的。這是解決方案:

import urllib.request 

def extractHTML(url): 
    f = open('temphtml.txt', 'w') 
    page = urllib.request.urlopen(url) 
    pagetext = str(page.read()) 
    f.write(pagetext) 
    f.close() 

extractHTML('https://www.google.com') 

你的腳本給出了一個錯誤,說它必須是一個字符串。只需將字節轉換爲str()的字符串即可。

接下來我收到一個錯誤,說沒有主機給出。 Google is a secured site so https: not http:,最重要的是你忘記了在https:的末尾包含//