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 etreesema = 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中,完成。
沒有特別突出的地方,簡單易操作。
轉載于:https://www.cnblogs.com/happymeng/p/10247882.html
總結
以上是生活随笔為你收集整理的Python爬虫入门教程 22-100 CSDN学院课程数据抓取的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: HackerRank python练习
- 下一篇: websocket python爬虫_p