惯例,美女镇楼!!

最近发现一个
python
异步IO支持库挺不错的,就是号称可以支持百万级别并发的asyncio
(真实性没验证过)。asyncio
是Python3.4
版本引入的标准库,直接内置了对异步IO的支持。asyncio
的编程模型就是一个消息循环。我们从asyncio
模块中直接获取一个EventLoop
的引用,然后把需要执行的协程扔到EventLoop
中执行,就实现了异步IO。异步编程相对于同步编程来说要复杂很多,主要是因为异步编程一般很难监测程序的实时执行情况,所以需要付出更多的努力在使用回调函数上。
下面简单的demo
个栗子来说明下asyncio
库使用的关键字及作用,作为比较我们先给出一个同步编程的栗子作为对比。
# 同步模式
import requests
def demo():
return requests.get('https://www.baidu.com')
print(demo())
接下来我们再来看看asyncio
模式:
import asyncio,aiohttp
async def demo():
async with aiohttp.ClientSession() as session:
response = await session.get('https://www.baidu.com')
content = await response.read()
return content
loop = asyncio.get_event_loop()
loop.run_until_complete(demo())
好了,一对比发现,卧槽,同样是简单的显示网页内容,asyncio
模式的代码比普通的同步模式要复杂多了,而且还出现了一堆什么async、asyncio、aiohttp、await
等关键字,搞得头都大!!别急,慢慢来分析,使用async
以及await
关键字将函数异步化。在demo()
中实际上有两个异步操作:首先异步获取网站响应,然后再通过异步读取响应的内容,当然使用read()
还可以读取图像等内容。
上面的代码中,我们创建了一个ClientSession
对象命名为session
,然后通过session
的get
方法得到一个 ClientResponse
对象,命名为session
,get
方法中传入了一个必须的参数url
,就是要获得源码的http url
。至此便通过协程完成了一个异步IO的get
请求。
aiohttp
推荐使用ClientSession
作为主要的接口发起请求,ClientSession
允许在多个请求之间保存cookie
以及相关对象信息。Session
(会话)在使用完毕之后需要关闭,关闭Session
是另一个异步操作,所以每次你都需要使用async with
关键字。一旦你建立了客户端session
,你可以用它发起请求。这里是又一个异步操作的开始。上下文管理器的with
语句可以保证在处理session
的时候,总是能正确的关闭它。要让你的程序正常的跑起来,你需要将他们加入事件循环中。所以你需要创建一个asyncio loop
的实例, 然后将任务加入其中。
假如我们将demo
中的content
改为content=response.read()
那么结果会怎样?结果可能是你期待获得响应对象,但是你得到的是一组生成器。这是因为response.read()
是一个异步操作,这意味着它不会立即返回结果,仅仅返回生成器。这些生成器需要被调用跟运行,但是这并不是默认行为。在Python34
中加入的yield from
以及Python35
中加入的await
便是为此而生。它们将迭代这些生成器。以上代码只需要在response.read()
前加上await
关键字即可修复。
访问多个链接
上面介绍的都是简单的一个url
,如果我们要顺序的访问多个url
该如何操作呢?先来看看同步模式是如何操作的:
for url in urls:
print(requests.get(url).text)
看起来是不是很简单,so easy!!但是,如果采用asyncio
异步模式就没这么简单了。来看看asyncio
模式下是如何实现:
loop = asyncio.get_event_loop()
tasks = [asyncio.ensure_future(url) for url in urls]
loop.run_until_complete(asyncio.wait(tasks))
看起来代码也很短,但是却出现了一堆函数,都不知道这些函数是干嘛的。现在我们来分析慢慢分析下。
首先,创建一个事件循环实例对象,接着我们要创建个tasks
任务列表,这里我们使用的是列表表达式来构建一个tasks
列表。不过我们需要将tasks
中的每个元素包装在asyncio
的Future
对象中,然后将Future
对象列表作为任务传递给事件循环。这样就可以顺序访问多个url
了。
胡乱分析了一波,算了,还是来个实例吧!
爬虫实例
这次我们选取的网站是unsplash
,这个网站上的图片质量还是挺高的,而我们这次采取的爬取内容方式也不是直接分析网页内容然后通过xpath
定位元素获取想要的内容,而是通过在请求加载过程中分析Network
信息获取api
信息,直接通过api
查询关键字keyword
获取内容。
- 分析
Network
获取api
信息
在chrome
浏览器中输入https://www.unsplash.com
点击进入unsplash
网站,再点击电脑上的F12
按键进入调试模式,在调试模式界面选中上面的Network
一栏
- 在
unsplash
网站界面的search
框中输入查询关键字,比如美女
,按电脑上的F5
键刷新网页,注意Network
下的变化,通过分析找到api
请求信息为https://unsplash.com/napi/search/photos?query=%E7%BE%8E%E5%A5%B3&xp=&per_page=20&page=1
- 通过对
api
请求信息的分析我们可以发现请求的时候还需要附带四个参数项
params={
'xp':'',
'per_page':20,
'page':1,
'query':str
}
点击分析得到的网址会发现返回的是一个json
格式的数据。接下来我们就可以通过之前的分析得到的信息进行code
了。

是不是看着这一大串信息头都大啊?别急,告诉你一个好的在线json格式查看工具
json editor online
,看看格式化后信息如何:
这下
json
信息是不是看起来清爽很多了!!我们关心的是 results
信息,再点击results
看看,
撸码
本着面向对象编程的思想,我们将这个爬虫程序封装成一个类Spider
,代码如下:
class Spider(object):
def __init__(self, query):#query为搜索的关键字
self.headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.2 (KHTML, like Gecko) '
'Chrome/22.0.1216.0 Safari/537.2',
}
self.num = 1
self.query = query
if self.query not in os.listdir('.'):
os.mkdir(self.query)
self.path = os.path.join(os.path.abspath('.'), self.query)
os.chdir(self.path) #切换到目标目录
def get_page_info(self, page):
'''获取json内容'''
url = 'https://unsplash.com/napi/search/photos'
data = {
'page': page,
'query': self.query,
'per_page': 20,
'xp':'',
}
response = requests.get(url, params=data)
if response.status_code == 200:#成功返回信息
return response.json()
else:
print('请求失败,状态码为{}'.format(response.status_code))
async def get_content(self, link):
'''获取link相应的内容'''
async with aiohttp.ClientSession() as session:
response = await session.get(link)
content = await response.read()
return content
async def download_img(self, img):
'''通过图片下载地址下载图片'''
content = await self.get_content(img[1])
with open(img[0] + '.jpg', 'wb') as f:
f.write(content)
print('下载第{}张图片成功!'.format(self.num))
self.num += 1
def run(self):
start = time.time()#记录起始时间戳
for i in range(1, 11):
results = self.get_page_info(i)['results']
print('hahha ....',results)
loop = asyncio.get_event_loop()
tasks = [asyncio.ensure_future(self.download_img((link['id'], link['links']['download']))) for link in
links]
loop.run_until_complete(asyncio.wait(tasks))
end = time.time()#获取结束时间戳
print('共运行了{}秒'.format(end - start))#程序耗时
至此,一个爬虫类所需的功能就封装完成了,下面就可以通过使用这个爬虫类在unsplash
网站上爬取图片了。
def main():
query = input('Please input you want to search keywords: ')
spider = Spider(query)
spider.run()
if __name__ == '__main__':
main()
爬虫运行后Terminal
显示的信息如下:

自动设置电脑壁纸
接下来我们换个玩法,我们将爬虫爬取的图片设置为电脑桌面,每隔5分钟自动更换一次电脑桌面图片。
用python
设置电脑桌面壁纸很简单,这些工作主要借助为win32api
和win32gui
这两个内置模块,我们一起来看具体代码:
def set_wallpaper(img_path):
# 打开指定注册表路径
reg_key = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, "Control Panel\\Desktop", 0, win32con.KEY_SET_VALUE)
# 最后的参数:2拉伸,0居中,6适应,10填充,0平铺
win32api.RegSetValueEx(reg_key, "WallpaperStyle", 0, win32con.REG_SZ, "2")
# 最后的参数:1表示平铺,拉伸居中等都是0
win32api.RegSetValueEx(reg_key, "TileWallpaper", 0, win32con.REG_SZ, "0")
# 刷新桌面 win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, img_path, win32con.SPIF_SENDWININICHANGE)
print('now change desktop wallpaper')
上面的方法传入的是壁纸的绝对路径,如何获取这个绝对路径img_path
呢?很简单,python
中的os
模块有个walk
方法,这个方法传入的是一个目录路径,参考代码如下(附注释):
def show_walk(dir_path):
for root,dirs,files in os.walk(dir_path, topdown=False):
for name in files:
print(os.path.join(root, name))
for name in dirs:
print(os.path.join(root, name))
# 返回的是一个三元tupple(root, dirs, files),其中第一个为起始路径,第二个为起始路径下的文件夹,第三个是起始路径下的文件。
# root是一个string,代表目录的路径,
# dirs是一个list,包含了dirpath下所有子目录的名字,
# files是一个list,包含了非目录文件的名字,这些名字不包含路径信息。如果需要得到全路径,需要使用 os.path.join(root, name)。
接下来我们就利用os.walk
来获取上面通过爬虫爬取的图片的绝对路径并返回一个包含该目录下的所有图片的路径的列表,参考代码如下:
def get_img_path():
print(os.getcwd()) #获取当前路径
path = os.path.join(os.getcwd(),'desktop-background')# desktop-background是爬虫程序里输入的query查询参数
print(path)
img_path = []
for root, dirs, files in os.walk(path):
for file in files:
img_path.append(os.path.join(root,file))
return img_path
最后来实现每隔5分钟自动更新电脑桌面壁纸功能,主要是通过random.choice()
方法传入图片地址列表随机获取上面返回的图片路径中的任意一张图片的路径来设置电脑桌面壁纸。具体的代码参考如下:
def auto_change_wallpaper():
img_path = get_img_path()
time_intvl = 5*60
start_time = int(time.time())
print(start_time)
while True:
end_time = int(time.time())
cost_time = end_time-start_time
if cost_time == time_intvl:
set_wallpaper(random.choice(img_path))
start_time = end_time
else:
pass
附上这个自动更换桌面壁纸的完整code
:
#!/usr/bin/env python
#-*-coding:utf-8-*-
import random
import win32api,win32gui,win32con
import time,os
def set_wallpaper(img_path):
# 打开指定注册表路径
reg_key = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, "Control Panel\\Desktop", 0, win32con.KEY_SET_VALUE)
# 最后的参数:2拉伸,0居中,6适应,10填充,0平铺
win32api.RegSetValueEx(reg_key, "WallpaperStyle", 0, win32con.REG_SZ, "2")
# 最后的参数:1表示平铺,拉伸居中等都是0
win32api.RegSetValueEx(reg_key, "TileWallpaper", 0, win32con.REG_SZ, "0")
# 刷新桌面
win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, img_path, win32con.SPIF_SENDWININICHANGE)
print('now change desktop wallpaper')
def get_img_path():
print(os.getcwd())
path = os.path.join(os.getcwd(),'desktop-background')
print(path)
img_path=[]
for root, dirs, files in os.walk(path):
for file in files:
img_path.append(os.path.join(root,file))
return img_path
def auto_change_wallpaper():
img_path=get_img_path()
time_intvl=5*60
start_time = int(time.time())
print(start_time)
while True:
end_time = int(time.time())
cost_time = end_time-start_time
if cost_time == time_intvl:
set_wallpaper(random.choice(img_path))
start_time = end_time
else:
pass
def main():
auto_change_wallpaper()
if __name__ == '__main__':
main()
好,瞎扯了这么多,就写到这里吧!

网友评论