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 etree

pool = ''

#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 data

except 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('

(.*?)(.*?)').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('解析详情页出错!')

pass

async 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)

continue

link = links_detail.pop()

if link not in crawled_links_detail:

asyncio.ensure_future(handle_elements(link, session))

async def main(loop):

global pool

pool = 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()

作者:Pykk2019

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

  1. python链家网高并发异步爬虫asyncio+aiohttp+aiomysql异步存入数据

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

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

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

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

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

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

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

  5. 链家网北京市租房数据分析(二)——基于python的数据可视化

    本次分析的数据为爬取链家网租房首页的3000余条整租房源数据.数据量较小,分析结果难免存在偏差,本分析报告仅作为实战项目展示.本报告中所描述的平均租金指单套房源租金的中位数. 数据源可至百度网盘提取, ...

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

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

  7. 链家网前端总架构师杨永林:我的8年架构师成长之路

    杨永林,人称"教主",八年前端开发经验,原新浪微博前端技术专家,现任链家网前端总架构师.长期研究Web访问性能优化和前端框架搭建. 作为初始团队成员,教主参与了新浪微博所有PC版本 ...

  8. python二手房使用教程_python实战:基于链家网二手房数据解析任务

    实战:基于链家网二手房数据解析任务 页面:https://bd.ke.com/ershoufang/ 获取如下信息: 标题 位置 房屋信息 关注人数 / 发布时间 房屋总价 房屋单价 备注信息 1.导 ...

  9. Python爬取链家网获取二手房数据并调用高德api获得经纬度

    链家网获得数据地址,高德api获得经纬度(同理链家网也可以换成其他58同城,赶集网的数据,因为反爬虫比较厉害,没时间整,就用链家网的数据先试试水) 首先爬链家网,Info包含一条信息 import j ...

最新文章

  1. yum工具安装Nginx
  2. 在ie8下ext显示的问题
  3. 《Head First设计模式》第九章(2)组合模式
  4. ghost网络克隆功能实现【批量】计算机操作【系统的安装】,网络学习(三十)通过ghost的网络克隆功能实现操作系统的分发...
  5. 现在很多人都在网上找富业
  6. VIM:使用js高亮对json文件着色
  7. 从青铜到王者的路线,javasocket编程聊天室
  8. UTC时间转北京时间
  9. 服务器连接无线键盘,【罗技 K375s 无线蓝牙键盘使用总结】连接|手感_摘要频道_什么值得买...
  10. 使用Python修改图片尺寸
  11. freemarer代码生成案例
  12. 浅谈:智能化变电站在线监测系统
  13. Praat脚本-029 | 一种更有效的校对音频内容的方案
  14. iOS Xcode 打包IPA问题集锦
  15. 游玩nds游戏的N种方法
  16. vue项目加入百度统计代码-统计网站浏览数据
  17. MySQL压缩包安装方法
  18. 关于python语言的注释以下描述错误的是_关于 Python 注释,以下选项中描述错误的是 ( )_学小易找答案...
  19. 在自家房子住了30年却被驱逐,区块链如何破解这一难题?
  20. 最新kali之curl(一)

热门文章

  1. Struts2 - 常用的constant总结
  2. 当前局域网禁止BT下载的常用工具及其弊端。
  3. sliverappbar高度,SliverAppBar的最小高度(颤振)?
  4. Hbase分布式列存储数据库
  5. 为何要使用大数据可视化平台
  6. JavaScript 自定义对象 及 new()原理与实现 如何完整地手写实现new
  7. 软件测试web和app,软件测试如何快速进阶?过来人科普Web与App测试5大区别!
  8. win7桌面运行html,手把手教你win7电脑如何运行config的操作教程
  9. php上传虚假图片,解决PHP上传多个图片并校验的代码问题
  10. win10卸载电脑管家就蓝屏_新电脑WIN10出现蓝屏 系统重装也不行