python - 爬蟲內(nèi)容保存成文本文件 編碼問題
問題描述
測(cè)試一個(gè)非常簡(jiǎn)單的爬蟲,把一個(gè)非常簡(jiǎn)約風(fēng)格的網(wǎng)頁的文本內(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)前小說第{}章已經(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)前小說第{}章已經(jīng)下載完成’.format(i)) ...: f.close() ...: i=i+1
問題解答
回答1:f.write(content.encode(’utf-8’))
或者
import codecswith codecs.open(filename, ’w’, ’utf-8’) as f: f.write(content)
相關(guān)文章:
1. css3 - sublime text2 的less2css插件怎么使用2. html5 - z-index在瀏覽器調(diào)試有效 手機(jī)測(cè)試無效3. 關(guān)于docker下的nginx壓力測(cè)試4. angular.js使用$resource服務(wù)把數(shù)據(jù)存入mongodb的問題。5. angular.js - angularjs的自定義過濾器如何給文字加顏色?6. docker-machine添加一個(gè)已有的docker主機(jī)問題7. 為什么我ping不通我的docker容器呢???8. docker - 如何修改運(yùn)行中容器的配置9. nignx - docker內(nèi)nginx 80端口被占用10. docker安裝后出現(xiàn)Cannot connect to the Docker daemon.
