python - 爬蟲內容保存成文本文件 編碼問題
問題描述
測試一個非常簡單的爬蟲,把一個非常簡約風格的網頁的文本內容保存到本地的電腦上。最后出現錯誤:
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(’當前小說第{}章已經下載完成’.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’)) ...: ...:#遍歷每個鏈接,下載文本內容到 本地文本文件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(’當前小說第{}章已經下載完成’.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)
相關文章:
1. javascript - 下面的這段算法代碼求解釋2. javascript - 在top.jsp點擊退出按鈕后,right.jsp進行頁面跳轉,跳轉到login.jsp3. javascript - js 有什么優雅的辦法實現在同時打開的兩個標簽頁間相互通信?4. android - 哪位大神知道java后臺的api接口的對象傳到前端后輸入日期報錯,是什么情況?求大神指點5. css3 - 在sublime text里, 如何讓emmet生成的帶前綴css屬性垂直對齊?6. mac連接阿里云docker集群,已經卡了2天了,求問?7. javascript - 回調函數和閉包的關系8. java - spring-data Jpa 不需要執行save 語句,Set字段就可以自動執行保存的方法?求解9. [前端求職必看]前端開發面試題與答案精選_擴展問題10. 想找個php大神仿個網站。
