Skip to main content
 首页 » 编程设计

Python Selenium 页面无法保存源代码编码错误

2024年10月01日7cmt

我正在尝试使用 Selenium 将源代码保存到 .txt 中,但 .txt 文件仍为空。

当我尝试使用命令打印源代码时:

htmlcode = driver.page_source 
(driver.page_source).encode('utf-8')) 
print(htmlcode) 

它将打印源代码,但随后会因错误而终止脚本:

File "C:\Python27\lib\encodings\cp850.py", line 12, in encode 
return codecs.charmap_encode(input,errors,encoding_map) 
UnicodeEncodeError: 'charmap' codec can't encode character u'\u20ac' in position 16329: character maps to <undefined> 

请您参考如下方法:

问题解决了!搜索 3 小时后 ':-)

html = driver.page_source 
f = open('savepage.html', 'w') 
f.write(html.encode('utf-8')) 
f.close()