我學會了如何從https://automatetheboringstuff.com中刪除網站。我想取消其中內容爲中文的http://www.piaotian.net/html/3/3028/1473227.html,並將其內容寫入.txt文件。但是,.txt文件包含隨機符號,我認爲這是一個編碼/解碼問題。拼音漢字python
我讀過這個主題「how to decode and encode web page with python?」,並認爲我的網站的編碼方法是「gb2312」和「windows-1252」。我試圖用這兩種編碼方法解碼,但失敗了。
有人可以向我解釋我的代碼問題嗎?我對編程非常陌生,所以請讓我知道我的錯誤觀念!
此外,當我從代碼中刪除「html.parser」時,.txt文件變成空的,而不是至少有符號。爲什麼會這樣?
import bs4, requests, sys
reload(sys)
sys.setdefaultencoding("utf-8")
novel = requests.get("http://www.piaotian.net/html/3/3028/1473227.html")
novel.raise_for_status()
novelSoup = bs4.BeautifulSoup(novel.text, "html.parser")
content = novelSoup.select("br")
novelFile = open("novel.txt", "w")
for i in range(len(content)):
novelFile.write(str(content[i].getText()))
您只需要在網站上找到正確的編碼並應用即可。這裏是關於agenty的詳細教程 - https://www.agenty.com/doc/hosted-app/248/scraping-chinese-or-japanese-websites –