保存的html文档中出现中文乱码:
代码:
from selenium import webdriver browser = webdriver.PhantomJS( ) url = 'http://music.163.com/#/playlist?id=11362719' browser.get(url) # 打开网页 browser.switch_to.frame(browser.find_element_by_xpath("//iframe")) #title = browser.find_elements_by_xpath('//*[@id="play-count"]') #title = browser.find_elements_by_xpath('//*tr/@class') #print(browser.page_source.encoding('utf-8')) print(browser.page_source,file=open('C:/Users/welwel/Desktop/source.html','w',encoding='utf-8')) browser.quit()
1.使用type(browser.page_source)查看类型是str,无法使用。decode转换格式
2.用的是win7下python3.5 的IDLE,使用sys.getdefaultencoding()查看默认编码是‘utf-8’
3.直接使用print(browser.page_source)报错:
Traceback (most recent call last): File "C:\Users\welwel\Desktop\wangyi.py", line 8, inprint(browser.page_source) File "C:\Python35-32\lib\idlelib\PyShell.py", line 1344, in write return self.shell.write(s, self.tags) UnicodeEncodeError: 'UCS-2' codec can't encode characters in position 55288-55288: Non-BMP character not supported in Tk
这个问题在第一次爬取网页时使用print(browser.page_source,file=open('C:/Users/welwel/Desktop/source.html','w',encoding='utf-8'))
不会报错,但是加在for循环中就会从第二个开始,出现中文乱码,不知是不是bug。有没有遇到过的。
好吧,我的需求是抓取歌曲的评论&歌曲名称,原本计划将网页爬下来慢慢正则,后来发现爬下来的网页先是第奇数中文正常,偶数中文乱码,(我要爬取50个网页),后来就反过来了。如此说来就是在win7上有bug,linux没装。根据需求使用xpath分析,
eg:
ele_com = browser.find_element_by_xpath("//p[@class='cnt f-brk']")
返回数据正常。还是在cmd上运行。
所以要是爬个数据就直接用模块上的工具就好了,不要瞎折腾
print(browser.page_source,file=open('C:/Users/welwel/Desktop/source.html','w'))
试试这样:
print(browser.page_source.encode('utf-8').decode(), file=open("xxx.html","w", encoding='utf-8'))