日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

Python爬虫入门教程 22-100 CSDN学院课程数据抓取

發布時間:2023/12/20 python 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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学院课程数据抓取的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。