1. 程式人生 > >Python爬蟲入門教程 22-100 CSDN學院課程資料抓取

Python爬蟲入門教程 22-100 CSDN學院課程資料抓取

1. CSDN學院課程資料-寫在前面

今天又要抓取一個網站了,選擇恐懼症使得我不知道該拿誰下手,找來找去,算了,還是抓取CSDN學院吧,CSDN學院的網站為 https://edu.csdn.net/courses 我看了一下這個網址,課程數量也不是很多,大概有 6000+ 門課程,資料量不大,用單執行緒其實就能很快的爬取完畢,不過為了秒爬,我還是選用了一個非同步資料操作。

在這裡插入圖片描述

2. CSDN學院課程資料-分析頁碼

還是需要好好的分析一下頁碼規律

https://edu.csdn.net/courses/p2
https://edu.csdn.net/courses/p3
https://edu.csdn.net/courses/p4
... ...
https://edu.csdn.net/courses/p271

頁碼還是非常有規律的,直接編寫程式碼就可以快速的爬取下來。出於人文關懷,我還是把協程數限制在3,要不順發271個請求還是有點攻擊的性質了。這樣不好,不符合我們的精神。

import asyncio
import aiohttp
from lxml import etree



sema = asyncio.Semaphore(3)
async def get_html(url):
    headers = {
        "user-agent": "自己找個UA即可"
    }
    '''
    本文來自 夢想橡皮擦 的部落格
    地址為:  https://blog.csdn.net/hihell  
    可以任意轉載,但是希望給我留個版權。
    '''
    print("正在操作{}".format(url))

    async with aiohttp.ClientSession() as s:
        try:
            async with s.get(url, headers=headers, timeout=3) as res:
                if res.status==200:
                    html = await res.text()

                    html = etree.HTML(html)
                    get_content(html)  # 解析網頁
                    print("資料{}插入完畢".format(url))

        except Exception as e:
            print(e)
            print(html)
            time.sleep(1)
            print("休息一下")
            await get_html(url)
            
async def x_get_html(url):
    with(await sema):
        await get_html(url)

if __name__ == '__main__':
    url_format = "https://edu.csdn.net/courses/p{}"
    urls = [url_format.format(index) for index in range(1, 272)]
    loop = asyncio.get_event_loop()
    tasks = [x_get_html(url) for url in urls]
    request = loop.run_until_complete(asyncio.wait(tasks))

3. CSDN學院課程資料-解析網頁函式

網頁下載到了之後,需要進行二次處理,然後才可以把他放入到mongodb中,我們只需要使用lxml庫即可

def get_content(html):
    course_item = html.xpath("//div[@class='course_item']")
    data = []
    for item in course_item:
        link = item.xpath("./a/@href")[0]  # 獲取課程詳情的連結,方便我們後面抓取
        tags = item.xpath(".//div[@class='titleInfor']/span[@class='tags']/text()")  # 獲取標籤
        title = item.xpath(".//div[@class='titleInfor']/span[@class='title']/text()")[0]  # 獲取標題
        num = item.xpath(".//p[@class='subinfo']/span/text()")[0]  # 學習人數
        subinfo = item.xpath(".//p[@class='subinfo']/text()")[1].strip() #  作者
        price = item.xpath(".//p[contains(@class,'priceinfo')]/i/text()")[0].strip()  # 作者
        data.append({
            "title":title,
            "link":link,
            "tags":tags,
            "num":num,
            "subinfo":subinfo,
            "price":price
        })

    collection.insert_many(data)

4. CSDN學院課程資料-資料儲存

資料儲存到mongodb中,完成。

在這裡插入圖片描述




沒有特別突出的地方,簡單易操作。