久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁技術(shù)文章
文章詳情頁

python - 爬蟲內(nèi)容保存成文本文件 編碼問題

瀏覽:121日期:2022-06-29 09:03:36

問題描述

測試一個非常簡單的爬蟲,把一個非常簡約風(fēng)格的網(wǎng)頁的文本內(nèi)容保存到本地的電腦上。最后出現(xiàn)錯誤:

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’)) ...: ...:#遍歷每個鏈接,下載文本內(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)

標(biāo)簽: Python 編程
相關(guān)文章:
主站蜘蛛池模板: 武平县| 新竹市| 静宁县| 上杭县| 徐水县| 田林县| 十堰市| 乌什县| 镇坪县| 崇阳县| 郧西县| 塘沽区| 石泉县| 陆川县| 新绛县| 鲁甸县| 平和县| 庄河市| 陆川县| 青铜峡市| 封丘县| 通辽市| 广水市| 康保县| 泰来县| 文昌市| 华阴市| 景东| 正镶白旗| 福鼎市| 佳木斯市| 安徽省| 同江市| 宝山区| 科技| 彝良县| 西昌市| 绥德县| 鹤壁市| 勃利县| 冷水江市|