行行網電子書多線程爬取


行行網電子書多線程爬取-寫在前面

最近想找幾本電子書看看,就翻啊翻,然后呢,找到了一個 叫做 周讀的網站 ,網站特別好,簡單清爽,書籍很多,而且打開都是百度網盤可以直接下載,更新速度也還可以,於是乎,我給爬了。本篇文章學習即可,這么好的分享網站,盡量不要去爬,影響人家訪問速度就不好了 http://www.ireadweek.com/ ,想要數據的,可以在我博客下面評論,我發給你,QQ,郵箱,啥的都可以。

在這里插入圖片描述

在這里插入圖片描述

這個網站頁面邏輯特別簡單 ,我翻了翻 書籍詳情頁面 ,就是下面這個樣子的,我們只需要循環生成這些頁面的鏈接,然后去爬就可以了,為了速度,我采用的多線程,你試試就可以了,想要爬取之后的數據,就在本篇博客下面評論,不要搞壞別人服務器。

http://www.ireadweek.com/index.php/bookInfo/11393.html http://www.ireadweek.com/index.php/bookInfo/11.html .... 

行行網電子書多線程爬取-擼代碼

代碼非常簡單,有咱們前面的教程做鋪墊,很少的代碼就可以實現完整的功能了,最后把采集到的內容寫到 csv 文件里面,(csv 是啥,你百度一下就知道了) 這段代碼是IO密集操作 我們采用aiohttp模塊編寫。

第1步

拼接URL,開啟線程。

import requests # 導入協程模塊 import asyncio import aiohttp headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36", "Host": "www.ireadweek.com", "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8"} async def get_content(url): print("正在操作:{}".format(url)) # 創建一個session 去獲取數據 async with aiohttp.ClientSession() as session: async with session.get(url,headers=headers,timeout=3) as res: if res.status == 200: source = await res.text() # 等待獲取文本 print(source) if __name__ == '__main__': url_format = "http://www.ireadweek.com/index.php/bookInfo/{}.html" full_urllist = [url_format.format(i) for i in range(1,11394)] # 11394 loop = asyncio.get_event_loop() tasks = [get_content(url) for url in full_urllist] results = loop.run_until_complete(asyncio.wait(tasks)) 

上面的代碼可以同步開啟N多個線程,但是這樣子很容易造成別人的服務器癱瘓,所以,我們必須要限制一下並發次數,下面的代碼,你自己嘗試放到指定的位置吧。

sema = asyncio.Semaphore(5) # 為避免爬蟲一次性請求次數太多,控制一下 async def x_get_source(url): with(await sema): await get_content(url)

第2步

處理抓取到的網頁源碼,提取我們想要的元素,我新增了一個方法,采用lxml進行數據提取。

def async_content(tree): title = tree.xpath("//div[@class='hanghang-za-title']")[0].text # 如果頁面沒有信息,直接返回即可 if title == '': return else: try: description = tree.xpath("//div[@class='hanghang-shu-content-font']") author = description[0].xpath("p[1]/text()")[0].replace("作者:","") if description[0].xpath("p[1]/text()")[0] is not None else None cate = description[0].xpath("p[2]/text()")[0].replace("分類:","") if description[0].xpath("p[2]/text()")[0] is not None else None douban = description[0].xpath("p[3]/text()")[0].replace("豆瓣評分:","") if description[0].xpath("p[3]/text()")[0] is not None else None # 這部分內容不明確,不做記錄 #des = description[0].xpath("p[5]/text()")[0] if description[0].xpath("p[5]/text()")[0] is not None else None download = tree.xpath("//a[@class='downloads']") except Exception as e: print(title) return ls = [ title,author,cate,douban,download[0].get('href') ] return ls 

第3步

數據格式化之后,保存到csv文件,收工!

 print(data)
 with open('hang.csv', 'a+', encoding='utf-8') as fw: writer = csv.writer(fw) writer.writerow(data) print("插入成功!") 

行行網電子書多線程爬取-運行代碼,查看結果

在這里插入圖片描述


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM