#aio 爬虫,去重,入库
import asyncio
import aiohttp
import aiomysql
import re
from pyquery import PyQuery stoping = False
start_url = 'http://www.jobbole.com/' waiting_urls = []
seen_urls = set()
# url去重 --布隆过滤器 bloom filter sem = asyncio.Semaphore(3) #限制并发数量 async def fetch(url,session):
async with sem:
#await asyncio.sleep(0.5)
try:
async with session.get(url) as resp:
print(resp.status)
if resp.status in [200,201]:
data = await resp.text()
return data
except Exception as e :
print(e) #因为不是耗费 io的 所以用普通函数
def extract_urls(html):
urls = []
pq = PyQuery(html)
for link in pq.items('a'):
url = link.attr('href')
if url and url.startswith('http') and url not in seen_urls:
urls.append(url)
waiting_urls.append(url)
return urls async def init_urls(url,session):
html = await fetch(url,session)
seen_urls.add(url)
extract_urls(html) async def article_handeler(url,session,pool):
#获取文章详情,并解析入库
html = await fetch(url,session)
seen_urls.add(url)
extract_urls(html)
pq = PyQuery(html)
title = pq('title').text()
async with pool.acquire() as conn:
async with conn.cursor() as cur:
await cur.execute('SELECT 42;')
insert_sql = 'insert into aiomysql_test(title) VALUES ("{}")'.format(title)
await cur.execute(insert_sql) async def consumer(pool):
async with aiohttp.ClientSession() as session:
while not stoping:
if len(waiting_urls) == 0:
await asyncio.sleep(0.5)
continue
url = waiting_urls.pop()
print('start get url:{}'.format(url))
if re.match('http://.*?jobbole.com/\d+/',url):
if url not in seen_urls:
asyncio.ensure_future(article_handeler(url,session,pool))
await asyncio.sleep(0.5)
else:
if url not in seen_urls:
asyncio.ensure_future(init_urls(url,session)) async def main(loop):
#等待mysql链接建立好
pool = await aiomysql.create_pool(host='127.0.0.1',port = 3306,
user = 'root',password='',
db = 'aiomysql_test',loop=loop,
charset = 'utf8',autocommit = True)
async with aiohttp.ClientSession() as session:
html = await fetch(start_url, session)
seen_urls.add(start_url)
extract_urls(html) asyncio.ensure_future(consumer(pool)) if __name__ == "__main__":
loop = asyncio.get_event_loop()
asyncio.ensure_future(main(loop))
loop.run_forever()

aio 爬虫,去重,入库的更多相关文章

  1. 笔记-爬虫-去重/bloomfilter

    笔记-爬虫-去重/bloomfilter 1.      去重 为什么要去重? 页面重复:爬的多了,总会有重复的页面,对已爬过的页面肯定不愿意再爬一次. 页面更新:很多页面是会更新的,爬取这种页面时就 ...

  2. [js高手之路]Node.js+jade+mongodb+mongoose实现爬虫分离入库与生成静态文件

    接着这篇文章[js高手之路]Node.js+jade抓取博客所有文章生成静态html文件继续,在这篇文章中实现了采集与静态文件的生成,在实际的采集项目中, 应该是先入库再选择性的生成静态文件.那么我选 ...

  3. scrapy-redis的搭建 分布式爬虫 去重

    master:一.spider文件1.需要更改继承的类from scrapy_redis.spiders import RedisSpider 2.注释掉start_urls 3.在爬虫目录下新创建一 ...

  4. Scrapy爬虫学习笔记 - 爬虫基础知识

    一.正则表达式 二.深度和广度优先                                三.爬虫去重策略

  5. 转载:爬虫技术浅析(Python)

    http://drops.wooyun.org/tips/3915 0x00 前言 网络爬虫(Web crawler),是一种“自动化浏览网络”的程序,或者说是一种网络机器人.它们被广泛用于互联网搜索 ...

  6. discuz数据批量入库接口

    近期在做社区,首选discuz,数据需要用scrapy爬虫批量入库,就写了一个php入库接口. <?php define('PW', 'abc123456');//一定要修改 if($_REQU ...

  7. scrapy补充-分布式爬虫

    spiders 介绍:在项目中是创建爬虫程序的py文件 #1.Spiders是由一系列类(定义了一个网址或一组网址将被爬取)组成,具体包括如何执行爬取任务并且如何从页面中提取结构化的数据. #2.换句 ...

  8. [js高手之路]Node.js+jade+mongoose实战todolist(分页,ajax编辑,删除)

    该系列文章索引: [js高手之路]node js系列课程-创建简易web服务器与文件读写 [js高手之路]node js系列课程-图解express+supervisor+ejs用法 [js高手之路] ...

  9. Redis入门_上

    Redis是基于内存的Key-Value数据库,包含Set.String.SortedSet.List.Hash等数据结构,可用于缓存.排名.爬虫去重等应用场景. 1.思维导图 2.安装与配置 2.1 ...

随机推荐

  1. Notes of the scrum meeting(12.9)

    meeting time:14:00~17:00p.m.,December 9th,2013 meeting place:一号教学楼209 attendees: 顾育豪                 ...

  2. SDUST OJ 时间类的加、减法赋值运算

    Problem F: 时间类的加.减法赋值运算 Time Limit: 3 Sec  Memory Limit: 128 MBSubmit: 3801  Solved: 2210[Submit][St ...

  3. java — 线程池

    线程池的作用       线程池作用就是限制系统中执行线程的数量.     根据系统的环境情况,可以自动或手动设置线程数量,达到运行的最佳效果:少了浪费了系统资源,多了造成系统拥挤效率不高.用线程池控 ...

  4. ZOJ 1666 G-Square Coins

    https://vjudge.net/contest/67836#problem/G People in Silverland use square coins. Not only they have ...

  5. <T extends Comparable<? super T>>

    在看Collections源代码中,看到如下代码: public static <T extends Comparable<? super T>> void sort(List ...

  6. 解决XAMPP中,MYSQL因修改my.ini后,无法启动的问题

    论这世上谁最娇贵,不是每年只开七天的睡火莲,也不是瑞典的维多利亚公主,更不是一到冬天就自动关机的iPhone 6s, 这世上最娇贵的,非XAMPP中的mysql莫属,记得儿时的我,年少轻狂,当时因为m ...

  7. 网络编程--System.Net

    using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; usin ...

  8. MySQL常用存储引擎功能与用法详解

    本文实例讲述了MySQL常用存储引擎功能与用法. MySQL存储引擎主要有两大类: 1. 事务安全表:InnoDB.BDB. 2. 非事务安全表:MyISAM.MEMORY.MERGE.EXAMPLE ...

  9. 使用 ECS 实例创建 FTP 站点 linux

    本文只做记载过程和问题,并不详细 官方教程走一遍 https://help.aliyun.com/document_detail/51998.html#h2-linux-ftp-2 值得注意的是步骤二 ...

  10. matlab中nargin函数的用法

    nargin是用来判断输入变量个数的函数,这样就可以针对不同的情况执行不同的功能. 通常可以用他来设定一些默认值,如下面的函数. 例子,函数test1的功能是输出a和b的和.如果只输入一个变量,则认为 ...