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

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

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

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

  2. 前端调用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. 链家网北京市租房数据分析(二)——基于python的数据可视化

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

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

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

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

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

  7. python爬取南京市房价_Python的scrapy之爬取链家网房价信息并保存到本地

    因为有在北京租房的打算,于是上网浏览了一下链家网站的房价,想将他们爬取下来,并保存到本地. 先看链家网的源码..房价信息 都保存在 ul 下的li 里面 ​ 爬虫结构: ​ 其中封装了一个数据库处理模 ...

  8. python+selenium爬取链家网房源信息并保存至csv

    python+selenium爬取链家网房源信息并保存至csv 抓取的信息有:房源', '详细信息', '价格','楼层', '有无电梯 import csv from selenium import ...

  9. python爬取链家房价消息_Python的scrapy之爬取链家网房价信息并保存到本地

    因为有在北京租房的打算,于是上网浏览了一下链家网站的房价,想将他们爬取下来,并保存到本地. 先看链家网的源码..房价信息 都保存在 ul 下的li 里面 ​ 爬虫结构: ​ 其中封装了一个数据库处理模 ...

最新文章

  1. 算法之智能搜索(下)
  2. java plt_matplotlib 画动态图以及plt.ion()和plt.ioff()的使用详解
  3. springmvc请求返回一个字符_SpringMVC系列之Web利器SpringMVC
  4. IOS学习笔记之十七 (NSDate、NSDateFormatter、NSCalendar、NSDateComponents、NSTimer)
  5. leetcode 1423. 可获得的最大点数(滑动窗口)
  6. C语言运行时数据结构
  7. DevOps(过程、方法与系统的统称)是什么
  8. u8 api开发报类型不匹配错误_小程序云开发入门学习,小程序支付功能常见错误汇总及解决方案...
  9. excel power bi 常用函数
  10. Vue移动端rotate强制横屏
  11. vp9 segment 详细分析
  12. 阿里技术专家甘盘:浅谈双十一背后的支付宝LDC架构和其CAP分析(含phil补充)
  13. [从头读历史] 第261节 左传 [BC657至BC598]
  14. Win10 OpenCV编译安装CUDA版本
  15. RAS 和 NDIS 拨号模式
  16. 木马核心技术剖析读书笔记之木马免杀
  17. python获取上一级目录
  18. 城际客车微信订票系统(固定线路拼车在线售票平台开发)
  19. 【嵌入式开发教程6】手把手教你做平板电脑-触摸屏驱动实验教程
  20. 老博会|2023第九届北京国际老年用品展览会

热门文章

  1. 基于SQL Server策略的管理–类别和数据库订阅
  2. sql索引调优_使用内置索引利用率指标SQL Server索引性能调优
  3. sql server 面试_SQL Server审核面试问题
  4. vue-devtoools 调试工具安装
  5. 一篇文章让你学透Linux系统中的more命令
  6. 基于sklearn进行文本向量化
  7. windows 安装 mysql 5.6
  8. mysqld.exe
  9. PHP 下载远程图片
  10. 如何实现Outlook 2010 下载邮件后自动删除服务器上的邮件