Python爬蟲入門教程 11-100 行行網電子書多線程爬取

寫在前面

最近想找幾本電子書看看,就翻啊翻,然後呢,找到了一個 叫做 周讀的網站 ,網站特別好,簡單清爽,書籍很多,而且打開都是百度網盤可以直接下載,更新速度也還可以,於是乎,我給爬了。本篇文章學習即可,這麼好的分享網站,儘量不要去爬,影響人家訪問速度就不好了 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("插入成功!")

運行代碼,查看結果

在這裏插入圖片描述

因爲這個可能涉及到獲取別人服務器重要數據了,代碼不上傳github了,有需要的留言吧,我單獨發送給你

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章