python - 爬蟲(chóng)內(nèi)容保存成文本文件 編碼問(wèn)題
問(wèn)題描述
測(cè)試一個(gè)非常簡(jiǎn)單的爬蟲(chóng),把一個(gè)非常簡(jiǎn)約風(fēng)格的網(wǎng)頁(yè)的文本內(nèi)容保存到本地的電腦上。最后出現(xiàn)錯(cuò)誤:
UnicodeEncodeErrorTraceback (most recent call last)<ipython-input-35-ead5570b2e15> in <module>() 7 filename=str(i)+’.txt’ 8 with open(filename,’w’)as f:----> 9 f.write(content) 10 print(’當(dāng)前小說(shuō)第{}章已經(jīng)下載完成’.format(i)) 11 f.close()UnicodeEncodeError: ’gbk’ codec can’t encode character ’xa0’ in position 7: illegal multibyte sequence
代碼如下:
In [1]: import requestsIn [2]: from bs4 import BeautifulSoupIn [3]: re=requests.get(’http://www.qu.la/book/168/’)In [4]: html=re.textIn [5]: soup=BeautifulSoup(html,’html.parser’)In [6]: list=soup.find(id='list')In [9]: link_list=list.find_all(’a’)In [14]: mylist=[] ...: for link in link_list: ...: mylist.append(’http://www.qu.la’+link.get(’href’)) ...: ...:#遍歷每個(gè)鏈接,下載文本內(nèi)容到 本地文本文件i=0 ...: for url in mylist1: ...: re1=requests.get(url) ...: html2=re1.text ...: soup=BeautifulSoup(html2,'html.parser') ...: content=soup.find(id='content').text.replace(’chaptererror();’, ’’) ...: filename=str(i)+’.txt’ ...: with open(filename,’w’)as f: ...: f.write(content) ...: print(’當(dāng)前小說(shuō)第{}章已經(jīng)下載完成’.format(i)) ...: f.close() ...: i=i+1
問(wèn)題解答
回答1:f.write(content.encode(’utf-8’))
或者
import codecswith codecs.open(filename, ’w’, ’utf-8’) as f: f.write(content)
相關(guān)文章:
1. 如何解決Centos下Docker服務(wù)啟動(dòng)無(wú)響應(yīng),且輸入docker命令無(wú)響應(yīng)?2. 我在centos容器里安裝docker,也就是在容器里安裝容器,報(bào)錯(cuò)了?3. vue ajax請(qǐng)求回來(lái)的數(shù)據(jù)沒(méi)有渲染到頁(yè)面4. mysql新建字段時(shí) timestamp NOT NULL DEFAULT ’0000-00-00 00:00:00’ 報(bào)錯(cuò)5. docker 17.03 怎么配置 registry mirror ?6. javascript - js 關(guān)于時(shí)間的轉(zhuǎn)換以及時(shí)間的加減。7. objective-c - IOS 分享到微信 提示 應(yīng)用消息數(shù)據(jù)錯(cuò)誤8. javascript - 音樂(lè)播放器-圖片旋轉(zhuǎn)9. angular.js - 用angularjs的service封裝百度地圖api出錯(cuò),請(qǐng)問(wèn)原因?10. MySQL timestamp的默認(rèn)值怎么設(shè)置?
