python网页数据抓取( 美国3.CSDN学院课程数据解析网页函数网页下载地址下载 )

优采云 发布时间: 2021-09-09 04:07

  python网页数据抓取(

美国3.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. 数据存储

  将数据保存到mongodb并完成。

  

  没有特别突出的地方,简单易操作。

  

0 个评论

要回复文章请先登录注册


官方客服QQ群

微信人工客服

QQ人工客服


线