win10, python3.6.5, selenium3.141.0, chrome 83.0.4103.61
說明:
參考了很多帖子尋找線索,謝謝各位。
現象:
訪問wenku頁面,看返回內容時,中文顯示有問題(字符串格式顯示,gbk各種編碼錯誤;字節格式顯示時,\x8e類代替漢字),儲存到文件時有問題(中文顯示不正常)。
(學習用。後續再多次訪問時,會按照人工訪問的時間間隔訪問)
辦法:
概括: 顯示時,用 io 更改輸出設定;
寫入文件時,用bytes 格式寫入文件(再電腦文本類軟件打開時中文顯示正常)。以字符串格式寫入文件,暫沒辦法搞定中文。
參考:
from selenium import webdriver
import time
import sys
import io
#更改系統顯示設置
sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf-8')
#測試網頁
url='https://wk.baidu.com/view/0caacb1e964bcf84b9d57be8?pcf=2'
#嘗試增加表頭(未完成)
options=webdriver.ChromeOptions()
options.add_argument('User-Agent="Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Mobile Safari/537.36" ')
driver1=webdriver.Chrome(options=options)
#訪問網頁
driver1.get(url)
#返回內容
pagesource=driver1.page_source
#顯示內容
print('pagesource:', pagesource, flush=True)
#存入文件
with open('pagesource.txt', 'wb') as f:
f.write(pagesource.encode('utf8'))