深圳集团网站开发,公司域名费用每年多少钱,仿古建筑公司网站,重庆网站建设公司在线联系1. CSDN学院课程数据-写在前面 今天又要抓取一个网站了#xff0c;选择恐惧症使得我不知道该拿谁下手#xff0c;找来找去#xff0c;算了#xff0c;还是抓取CSDN学院吧#xff0c;CSDN学院的网站为 https://edu.csdn.net/courses 我看了一下这个网址#xff0c;课程数量… 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, headersheaders, timeout3) as res:if res.status200: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[classcourse_item])data []for item in course_item:link item.xpath(./a/href)[0] # 获取课程详情的链接方便我们后面抓取tags item.xpath(.//div[classtitleInfor]/span[classtags]/text()) # 获取标签title item.xpath(.//div[classtitleInfor]/span[classtitle]/text())[0] # 获取标题num item.xpath(.//p[classsubinfo]/span/text())[0] # 学习人数subinfo item.xpath(.//p[classsubinfo]/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