aiohttp_spider
aiohttp_spider_def:
import asyncio
import re
import aiohttp
import aiomysql
from pyquery import PyQuery
from lxml import etree
start_url = 'http://news.baidu.com/'
waitting_urs = []
seen_uels = set()
stoppint = False
sem = asyncio.Semaphore(10) # 现在并发为3个
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko"}
async def fetch(url, session):
async with sem:
# await asyncio.sleep(1)
try:
async with session.get(url, headers=headers, timeout=1) as resp:
print('url status:{}'.format(resp.status))
# if resp.status in [200, 201]:
data = etree.HTML(await resp.read())
return data
except Exception as e:
print('错误为:{} url:{}'.format(e, url))
def extract_urls(html):
try:
for url in html.xpath('//a/@href'):
if url and url.startswith("http") and url not in seen_uels:
if re.findall(r'baidu', url):
waitting_urs.append(url)
except:
pass
async def init_urls(url, session):
html = await fetch(url, session)
seen_uels.add(url)
extract_urls(html)
async def article_handler(url, session, pool):
# 获取文章详情
html = await fetch(url, session)
seen_uels.add(url)
extract_urls(html)
try:
title = html.xpath('//title/text()')[0].strip()
print('title:{}'.format(title))
async with pool.acquire() as conn:
async with conn.cursor() as cursor:
try:
# 插入
await cursor.execute('insert into async_test_async(title) values("{}")'.format(title))
# 插入数据
await cursor.execute("insert into async_test_async(title) values('{}')".format(title))
# 查询数据
await cursor.execute("select * from async_test_async")
data = await cursor.fetchall()
print("data:", data)
# 更新数据
await cursor.execute("update async_test_async set title='{}' where id={}".format('update', 10168))
# 删除数据
await cursor.execute("delete from async_test_async where id={}".format(10174))
except:
pass
except:
pass
async def consumer(pool):
async with aiohttp.ClientSession() as session:
while not stoppint:
if len(waitting_urs) < 10:
if url not in seen_uels:
asyncio.ensure_future(init_urls(url, session))
url = waitting_urs.pop()
print('start get url:{}'.format(url))
if re.findall(r'baidu', url):
if url not in seen_uels:
print('waitting_urs:{}'.format(waitting_urs[0: 3]))
asyncio.ensure_future(article_handler(url, session, pool))
await asyncio.sleep(0.1)
async def main(loop):
pool = await aiomysql.create_pool(host='127.0.0.1', port=3306, user='root', password='root', db='cfda', loop=loop,
charset='utf8', autocommit=True)
async with aiohttp.ClientSession() as session:
html = await fetch(start_url, session)
seen_uels.add(start_url)
extract_urls(html)
asyncio.ensure_future(consumer(pool))
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.run_until_complete(main(loop))
loop.run_forever()
aiohttp_spider_class:
import asyncio
import re
import aiohttp
import aiomysql
from pyquery import PyQuery
from lxml import etree
start_url = 'http://news.baidu.com/'
waitting_urs = []
seen_uels = set()
stoppint = False
sem = asyncio.Semaphore(10) # 现在并发为3个
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko"}
class async_text(object):
async def fetch(self, url, session):
print("self:", self)
async with sem:
# await asyncio.sleep(1)
try:
async with session.get(url, headers=headers, timeout=1) as resp:
print('url status:{}'.format(resp.status))
# if resp.status in [200, 201]:
data = etree.HTML(await resp.read())
return data
except Exception as e:
print('错误为:{} url:{}'.format(e, url))
def extract_urls(self, html):
try:
for url in html.xpath('//a/@href'):
if url and url.startswith("http") and url not in seen_uels:
if re.findall(r'baidu', url):
waitting_urs.append(url)
except:
pass
async def init_urls(self, url, session):
html = await self.fetch(self, url, session)
seen_uels.add(url)
self.extract_urls(self, html)
async def article_handler(self, url, session, pool):
# 获取文章详情
html = await self.fetch(self, url, session)
seen_uels.add(url)
self.extract_urls(self, html)
try:
title = html.xpath('//title/text()')[0].strip()
print('title:{}'.format(title))
async with pool.acquire() as conn:
async with conn.cursor() as cur:
try:
# 插入
await cur.execute('insert into async_test_async(title) values("{}")'.format(title))
except:
pass
except:
pass
async def consumer(self, pool):
async with aiohttp.ClientSession() as session:
while not stoppint:
if len(waitting_urs) < 10:
if url not in seen_uels:
asyncio.ensure_future(self.init_urls(self, url, session))
url = waitting_urs.pop()
print('start get url:{}'.format(url))
if re.findall(r'baidu', url):
if url not in seen_uels:
print('waitting_urs:{}'.format(waitting_urs[0: 3]))
asyncio.ensure_future(self.article_handler(self, url, session, pool))
await asyncio.sleep(0.1)
@classmethod
async def main(self, loop):
pool = await aiomysql.create_pool(host='127.0.0.1', port=3306, user='root', password='root', db='cfda',
loop=loop,
charset='utf8', autocommit=True)
async with aiohttp.ClientSession() as session:
html = await self.fetch(self, start_url, session)
seen_uels.add(start_url)
self.extract_urls(self, html)
asyncio.ensure_future(self.consumer(self, pool))
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.run_until_complete(async_text.main(loop))
loop.run_forever()
aiohttp_spider的更多相关文章
随机推荐
- STL 中 string 的使用
赋值 string 类型变量可以直接赋值 str = "string"; // str 是 一个 string 类型变量 //等价于 str.assign("string ...
- #undef常用法
Copy from C语言中#undef的语法是: #undef 标识符 用来将前面定义的宏标识符取消定义. 整理了如下几种常见用法,如果以后发现其他的再添加进来. 1.在一个程序块中用完宏定义后,为 ...
- HDU2899Strange fuction(二分/三分)
传送门 题目大意:求 F(x) = 6 * x^7+8*x^6+7*x^3+5*x^2-y*x (0 <= x <=100):的最小值 题解:求个导,二分导函数零点,就是原函数最小值所在的 ...
- 关于powermock报错org.powermock.reflect.exceptions.FieldNotFoundException: Field 'fTestClass' was not found in class org.junit.internal.runners.MethodValidator.问题解决
事件背景 使用PowerMock模拟一个局部变量,添加@RunWith(PowerMockRunner.class).@PrepareForTest(StudentService.class)注解成功 ...
- jQuery 源码分析(十四) 数据操作模块 类样式操作 详解
jQuery的属性操作模块总共有4个部分,本篇说一下第3个部分:类样式操作部分,用于修改DOM元素的class特性的,对于类样式操作来说,jQuery并没有定义静态方法,而只定义了实例方法,如下: a ...
- 实现拖拽列表-微信小程序
之前在网上搜索拖拽列表的实现时,发现了有好多的方法都是基于像素位置的计算实现的,这种方法要求列表元素的大小以及列表的位置有着非常严格的要求,修改和拓展起来非常的麻烦.于是我自己动手实现了一个基于页面元 ...
- 【HDU6037】Expectation Division(动态规划,搜索)
[HDU6037]Expectation Division(动态规划,搜索) 题面 Vjudge 你有一个数\(n\),\(n\le 10^{24}\),为了方便会告诉你\(n\)分解之后有\(m\) ...
- Z从壹开始前后端分离【 .NET Core2.2/3.0 +Vue2.0 】框架之九 || 依赖注入IoC学习 + AOP界面编程初探
本文梯子 本文3.0版本文章 更新 代码已上传Github+Gitee,文末有地址 零.今天完成的绿色部分 一.依赖注入的理解和思考 二.常见的IoC框架有哪些 1.Autofac+原生 2.三种注入 ...
- Python3---爬虫---抓取百度贴吧
前言 该文章主要描述如何抓取百度贴吧内容.当然是简单爬虫实现功能,没有实现输入参数过滤等辅助功能,仅供小白学习. 修改时间:20191219 天象独行 import os,urllib.request ...
- opencv::证件照背景替换
证件照背景替换 K-Means 背景融合 – 高斯模糊 遮罩层生成 #include <opencv2/opencv.hpp> #include <iostream> usin ...