Python 爬蟲學習3 -簡單抓取小說網資訊

來源:互聯網
上載者:User

標籤:except   end   ISE   bsp   books   tor   cep   python 爬蟲   lin   

小說網 https://www.qu.la/paihangbang/

功能:抓取每個熱門排行榜內的小說名和對應連結,然後寫入excel表格裡面。

按F12 審查頁面元素可以得到你所要的資訊的class,從而來定位。

具體看代碼講解吧。

#coding:utf-8  #為了正常轉碼 必寫import codecs  #為下面建立excel,轉碼正確準備得一個包__author__ = ‘Administrator‘import requestsfrom bs4 import BeautifulSoup"""
get_html函數是為了抓取對應url的html頁面,然後返回這個頁面。
其實也可以全部寫入一個函數,不過這樣就會顯得函數很臃腫。
將這種公用函數獨立來寫,進行封裝,有助於以後重複利用。
"""def get_html(url): try: r = requests.get(url,timeout = 3000) r.raise_for_status r.encoding = ‘utf-8‘ return r.text except: return"""
get_content函數是用來提取你所需要的資訊的,並把資訊寫入excel表格。
"""def get_content(url):    url_list = []    html = get_html(url).encode(‘utf-8‘)    soup = BeautifulSoup(html, "html.parser")    category_list = soup.find_all(‘div‘, class_=‘index_toplist mright mbottom‘)    history_list = soup.find_all(‘div‘, class_ = ‘index_toplist mbottom‘)    for cate in category_list:        name = cate.find(‘div‘, class_ = ‘toptab‘).span.text        name = name.encode(‘utf-8‘)        with codecs.open(‘novel_list.csv‘,‘a+‘,‘utf-8‘) as f:            f.write(‘\n小說種類:{}\n‘.format(name))        book_list = cate.find(‘div‘, class_ = ‘topbooks‘).find_all(‘li‘)        for book in book_list:            link = ‘http://www.qu.la/‘+book.a[‘href‘]            title = book.a[‘title‘].encode(‘utf-8‘)            url_list.append(link)            with codecs.open(‘novel_list.csv‘,‘a+‘,‘utf-8‘) as f:                f.write(‘小說名:{} \t 小說地址:{}\n‘.format(title,link))    for cate in history_list:        name = cate.find(‘div‘, class_=‘toptab‘).span.string        with codecs.open(‘novel_list.csv‘,‘a+‘,‘utf-8‘) as f:            f.write("\n小說種類:{} \n".format(name))        general_list = cate.find(style=‘display: block;‘) #找到總熱門排行榜        book_list = general_list.find_all(‘li‘)        for book in book_list:            link = ‘http://www.qu.la/‘ + book.a[‘href‘]            title = book.a[‘title‘]            url_list.append(link)            with codecs.open(‘novel_list.csv‘,‘a+‘,‘utf-8‘) as f:                f.write("小說名:{:<} \t 小說地址:{:<} \n".format(title, link))    return url_listdef main():    # 熱門排行榜地址    base_url = ‘http://www.qu.la/paihangbang/‘    # 擷取熱門排行榜中所有小說連結    url_list = get_content(base_url)if __name__==‘__main__‘:    main()

本次主要是記錄編碼問題。

編寫完後run完出來是一個亂碼的excel表格

然後就開始進行debug

在每一步設定斷點,觀察每個變數 name title這些到底是用什麼編碼

現在這個版本,我基本是都加上了.encode(‘utf-8‘)

出來時每一個都是string變數

可是加了後還是亂碼。

然後我嘗試把資訊寫入txt文檔,發現成功了。

所以問題在於寫入excel,excel不能正確編碼,所以我改成了codecs.open(‘novel_list.csv‘,‘a‘,‘utf-8‘) 

最終成功解決問題。

思路僅供參考 編碼問題一直都會有,真的是頭大。

Python 爬蟲學習3 -簡單抓取小說網資訊

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.