python链家网二手房异步IO爬虫,使用asyncio、aiohttp和aiomysql

很多小伙伴初学python时都会学习到爬虫,刚入门时会使用requests、urllib这些同步的库进行单线程爬虫,速度是比较慢的,后学会用scrapy框架进行爬虫,速度很快,原因是scrapy是基于twisted多线程异步IO框架。
本例使用的asyncio也是一个异步IO框架,在python3.5以后加入了协程的关键字async,能够将协程和生成器区分开来,更加方便使用协程。
经过测试,平均1秒可以爬取30个详情页信息
可以使用asyncio.Semaphore来控制并发数,达到限速的效果

# -*- coding: utf-8 -*-
""":author: KK:url: http://github.com/PythonerKK:copyright: © 2019 KK <705555262@qq.com.com>
"""
import asyncio
import re
import aiohttp
from pyquery import PyQuery
import aiomysql
from lxml import etreepool = ''
#sem = asyncio.Semaphore(4)  用来控制并发数,不指定会全速运行
stop = False
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36'
}
MAX_PAGE = 10
TABLE_NAME = 'data'  #数据表名
city = 'zh'  #城市简写
url = 'https://{}.lianjia.com/ershoufang/pg{}/'  #url地址拼接
urls = []  #所有页的url列表
links_detail = set()  #爬取中的详情页链接的集合
crawled_links_detail = set()  #爬取完成的链接集合,方便去重async def fetch(url, session):'''aiohttp获取网页源码'''# async with sem:try:async with session.get(url, headers=headers, verify_ssl=False) as resp:if resp.status in [200, 201]:data = await resp.text()return dataexcept Exception as e:print(e)def extract_links(source):'''提取出详情页的链接'''pq = PyQuery(source)for link in pq.items("a"):_url = link.attr("href")if _url and re.match('https://.*?/\d+.html', _url) and _url.find('{}.lianjia.com'.format(city)):links_detail.add(_url)print(links_detail)def extract_elements(source):'''提取出详情页里面的详情内容'''try:dom = etree.HTML(source)id = dom.xpath('//link[@rel="canonical"]/@href')[0]title = dom.xpath('//title/text()')[0]price = dom.xpath('//span[@class="unitPriceValue"]/text()')[0]information = dict(re.compile('<li><span class="label">(.*?)</span>(.*?)</li>').findall(source))information.update(title=title, price=price, url=id)print(information)asyncio.ensure_future(save_to_database(information, pool=pool))except Exception as e:print('解析详情页出错!')passasync def save_to_database(information, pool):'''使用异步IO方式保存数据到mysql中注:如果不存在数据表,则创建对应的表'''COLstr = ''  # 列的字段ROWstr = ''  # 行字段ColumnStyle = ' VARCHAR(255)'for key in information.keys():COLstr = COLstr + ' ' + key + ColumnStyle + ','ROWstr = (ROWstr + '"%s"' + ',') % (information[key])# 异步IO方式插入数据库async with pool.acquire() as conn:async with conn.cursor() as cur:try:await cur.execute("SELECT * FROM  %s" % (TABLE_NAME))await cur.execute("INSERT INTO %s VALUES (%s)"%(TABLE_NAME, ROWstr[:-1]))print('插入数据成功')except aiomysql.Error as e:await cur.execute("CREATE TABLE %s (%s)" % (TABLE_NAME, COLstr[:-1]))await cur.execute("INSERT INTO %s VALUES (%s)" % (TABLE_NAME, ROWstr[:-1]))except aiomysql.Error as e:print('mysql error %d: %s' % (e.args[0], e.args[1]))async def handle_elements(link, session):'''获取详情页的内容并解析'''print('开始获取: {}'.format(link))source = await fetch(link, session)#添加到已爬取的集合中crawled_links_detail.add(link)extract_elements(source)async def consumer():'''消耗未爬取的链接'''async with aiohttp.ClientSession() as session:while not stop:if len(urls) != 0:_url = urls.pop()source = await fetch(_url, session)print(_url)extract_links(source)if len(links_detail) == 0:print('目前没有待爬取的链接')await asyncio.sleep(2)continuelink = links_detail.pop()if link not in crawled_links_detail:asyncio.ensure_future(handle_elements(link, session))async def main(loop):global poolpool = await aiomysql.create_pool(host='127.0.0.1', port=3306,user='root', password='xxxxxx',db='aiomysql_lianjia', loop=loop, charset='utf8',autocommit=True)for i in range(1, MAX_PAGE):urls.append(url.format(city, str(i)))print('爬取总页数:{} 任务开始...'.format(str(MAX_PAGE)))asyncio.ensure_future(consumer())if __name__ == '__main__':loop = asyncio.get_event_loop()asyncio.ensure_future(main(loop))loop.run_forever()

python链家网高并发异步爬虫asyncio+aiohttp+aiomysql异步存入数据相关推荐

  1. python链家网高并发异步爬虫and异步存入数据

    python链家网二手房异步IO爬虫,使用asyncio.aiohttp和aiomysql 很多小伙伴初学python时都会学习到爬虫,刚入门时会使用requests.urllib这些同步的库进行单线 ...

  2. aiohttp保存MySQL_python链家网高并发异步爬虫asyncio+aiohttp+aiomysql异步存入数据

    python链家网二手房异步IO爬虫,使用asyncio.aiohttp和aiomysql 很多小伙伴初学python时都会学习到爬虫,刚入门时会使用requests.urllib这些同步的库进行单线 ...

  3. 前端调用mysql异步_python链家网高并发异步爬虫asyncio+aiohttp+aiomysql异步存入数据...

    python链家网二手房异步IO爬虫,使用asyncio.aiohttp和aiomysql 很多小伙伴初学python时都会学习到爬虫,刚入门时会使用requests.urllib这些同步的库进行单线 ...

  4. aiohttp mysql_python异步爬虫asyncio+aiohttp+aiomysql异步存入数据

    异步IO爬虫,使用asyncio.aiohttp和aiomysql 很多小伙伴初学python时都会学习到爬虫,刚入门时会使用requests.urllib这些同步的库进行单线程爬虫,速度是比较慢的, ...

  5. python链家网爬虫_手把手教你利用Python网络爬虫获取链家网的房产信息

    点击上方" Python爬虫与数据挖掘 ",进行关注 回复"书籍"即可获赠Python从入门到进阶共10本电子书 今 日 鸡 汤 夜阑卧听风吹雨,铁马冰河入梦来 ...

  6. python asyncio与aiohttp_python链家网异步IO爬虫,使用asyncio、aiohttp和aiomysql

    python链家网异步IO爬虫,使用asyncio.aiohttp和aiomysql 平均1秒可以爬取30个详情页信息 可以使用asyncio.Semaphore来控制并发数,达到限速的效果 # -* ...

  7. Python 小项目 01 爬虫项目 爬取链家网南京地区二手房信息

    SpiderLianjia 介绍 python爬虫小程序,爬取链家网南京地区普通住宅二手房数据. 代码下载: https://gitee.com/lihaogn/SpiderLianjia 1 程序设 ...

  8. 手把手教你利用Python网络爬虫获取链家网的房产信息

    点击上方"Python爬虫与数据挖掘",进行关注 回复"书籍"即可获赠Python从入门到进阶共10本电子书 今 日 鸡 汤 夜阑卧听风吹雨,铁马冰河入梦来. ...

  9. Python爬虫攻略(2)Selenium+多线程爬取链家网二手房信息

    申明:本文对爬取的数据仅做学习使用,请勿使用爬取的数据做任何商业活动,侵删 前戏 安装Selenium: pip install selenium 如果下载速度较慢, 推荐使用国内源: pip ins ...

最新文章

  1. Linux shell初识及权限理解
  2. java冒泡怎么写_java 冒泡 又一种写法
  3. 标准C程序设计七---05
  4. 架构篇:高可用 Redis 服务架构分析与搭建
  5. 全面了解CCD摄像机
  6. JDK有三种字体绘制系统
  7. 计算机视觉论文-2021-07-28
  8. 指针数组与二维数组指针的本质区别
  9. Mysql数据库内对查询结果去重复指令【重点】
  10. 巨人肩膀上的迁移学习(2)---图像回归
  11. 计算机系统存储器 分类,存储器的分类
  12. 敏锐嗅出商机,她瞄准花卉市场的空白,将花店开出名气
  13. window10 1060 caffe 安装
  14. Python 爬虫实战(1)
  15. 微信公众平台开发教程(一) 微信公众账号注册流程
  16. Angular 组件类测试
  17. coreldraw怎么画猴子_小猴头像简笔画【CDR11设计制作逼真的小猴头像实例教程】...
  18. UI设计师有哪些就业方向选择?
  19. 嘉立创EDA专业版--PCB器件重叠如何选中
  20. 分布式文件系统mogileFS

热门文章

  1. jsp指令元素与动作元素
  2. 【LeetCode】LeetCode之乘积为正数的最长子数组长度——暴力枚举+动态规划+Kadane算法
  3. Spring Boot——易班优课YOOC课群在线测试自动答题解决方案(三)答案查询
  4. Vue + Element UI——侧边栏LOGO设计DEMO
  5. C#——委托(delegate)DEMO
  6. Machine Schedule
  7. [USACO08DEC]在农场万圣节Trick or Treat on the Farm
  8. 测试软件ipc,IPC整机测试工具
  9. XCode 4.2(4.1)真机调试及生成IPA全攻略
  10. Android RecyclerView 性能优化总结