效率的提升,代码的精简,Bug的消失,想必是大多数程序猿最终希望的样子。无论是开发,还是数据挖掘等等,最后的最后都是需要扩展自己的知识层面来解决相关问题或是得到相关高人的指点。相信你们看完我这篇文章,会对异步感兴趣的。
速度快得离谱!异步抓取贝壳房价信息数据
本文爬取网站为贝壳 链接
第一步 简单分析网站
翻转第二页 寻找网站异步请求的数据
虽然都是一些看不懂的,但是我们知道他是json格式,给它粘贴到网上去格式化(json 在线解析)
链接
如下图格式化完的数据
容易看出我们需要的数据就在List 中
第二步提取我们所需的信息
async def get_content(session, url):
"""
解析数据并提取相关内容
"""
item = await fetch(session, url)
data = re.findall(r"\"list\":(.+?),\"switch_city\"", str(item))
jsonObj = json.loads(data[0])
# print(jsonObj) # for test
hourse_data = []
for t in jsonObj:
house_info = {
'区': t['district'],
'标题': t['title'],
'小区地址': t['address'],
'均价': t['show_price_info'],
'Tags': t['tags'],
'房屋类型': t['house_type'],
'最低总价': t['lowest_total_price'],
'装饰程度': t['decoration'],
'建筑面积': t['resblock_frame_area'],
'户型': t['frame_rooms_desc'],
'总价': t['reference_total_price'] + t['reference_total_price_unit']
}
hourse_data.append(house_info)
return hourse_data
第三步存储至数据库中,这里采用异步的数据库存储
async def saveToAiomysql(session, url):
"""
存储数据
"""
data = await get_content(session, url)
conn = await aiomysql.connect(host='127.0.0.1', user='root', password='123123', db='save_data', port=3306,
)
async with conn.cursor() as cur:
print("——————————————————正在插入数据中——————————————————————")
for i in data:
inser_sql = "INSERT INTO Hourse_info(" \
"area,title,address,average_price,tags,house_type,lowest_total_price,decoration,resblock_frame_area,frame_rooms_desc,total_price_range" \
")values(%s,%s,%s,%s,%r,%s,%s,%s,%s,%s,%s)" % (
repr(i['区']), repr(i['标题']), repr(i['小区地址']), repr(i['均价']), repr(i['Tags']),
repr(i['房屋类型']),
repr(i['最低总价']),
repr(i['装饰程度']), repr(i['建筑面积']), repr(i['户型']), repr(i['总价']))
await cur.execute(inser_sql)
await conn.commit()
print("————————————————插入成功——————————————")
conn.close()
最终效果如下
本文代码可以共享,需要请评论或私聊