一 利用生成器来完成爬去校花网视频

  

import requests
import re
import os
import hashlib
import time DOWLOAD_PATH=r'D:\DOWNLOAD' def get_page(url):
try:
response=requests.get(url,)
if response.status_code == 200:
return response.text
except Exception:
pass def parse_index(index_contents):
# print(type(index_contents))
detail_urls=re.findall('class="items".*?href="(.*?)"',index_contents,re.S)
for detail_url in detail_urls:
if not detail_url.startswith('http'):
detail_url='http://www.xiaohuar.com'+detail_url
yield detail_url def parse_detail(detail_contents):
movie_urls=re.findall('id="media".*?src="(.*?)"',detail_contents,re.S)
if movie_urls:
movie_url=movie_urls[0]
if movie_url.endswith('mp4'):
yield movie_url def download(movie_url):
print(movie_url)
try:
response=requests.get(movie_url,
)
if response.status_code == 200:
data=response.content
m=hashlib.md5()
m.update(str(time.time()).encode('utf-8'))
m.update(movie_url.encode('utf-8'))
filepath=os.path.join(DOWLOAD_PATH,'%s.mp4' %m.hexdigest())
with open(filepath,'wb') as f:
f.write(data)
f.flush()
print('下载成功',movie_url)
except Exception:
pass def main():
raw_url='http://www.xiaohuar.com/list-3-{page_num}.html'
for i in range(5):
#请求索引页,解析拿到详情页链接
index_url=raw_url.format(page_num=i)
index_contents=get_page(index_url)
detail_urls=parse_index(index_contents) #请求详情页,解析拿到视频的链接地址
for detail_url in detail_urls:
detail_contents=get_page(detail_url)
movie_urls=parse_detail(detail_contents) #下载视频
for movie_url in movie_urls:
download(movie_url) if __name__ == '__main__':
t1=time.time()
main()
print(time.time()-t1)

二 利用对线程优化上述代码

  

import requests #pip install requests
import re
import os
import hashlib
import time
from concurrent.futures import ThreadPoolExecutor pool=ThreadPoolExecutor(50)
DOWLOAD_PATH=r'D:\DOWNLOAD' def get_page(url):
try:
response=requests.get(url,)
if response.status_code == 200:
return response.text
except Exception:
pass def parse_index(index_contents):
index_contents=index_contents.result()
detail_urls=re.findall('class="items".*?href="(.*?)"',index_contents,re.S)
for detail_url in detail_urls:
if not detail_url.startswith('http'):
detail_url='http://www.xiaohuar.com'+detail_url
pool.submit(get_page,detail_url).add_done_callback(parse_detail) def parse_detail(detail_contents):
detail_contents=detail_contents.result()
movie_urls=re.findall('id="media".*?src="(.*?)"',detail_contents,re.S)
if movie_urls:
movie_url=movie_urls[0]
if movie_url.endswith('mp4'):
pool.submit(download,movie_url) def download(movie_url):
# print(movie_url)
try:
response=requests.get(movie_url,
)
if response.status_code == 200:
data=response.content
m=hashlib.md5()
m.update(str(time.time()).encode('utf-8'))
m.update(movie_url.encode('utf-8'))
filepath=os.path.join(DOWLOAD_PATH,'%s.mp4' %m.hexdigest())
with open(filepath,'wb') as f:
f.write(data)
f.flush()
print('下载成功',movie_url)
except Exception:
pass def main():
raw_url='http://www.xiaohuar.com/list-3-{page_num}.html'
for i in range(5):
#请求索引页,解析拿到详情页链接
index_url=raw_url.format(page_num=i)
pool.submit(get_page,index_url).add_done_callback(parse_index) if __name__ == '__main__':
t1=time.time()
main()
print(time.time()-t1)

牛逼的代码

三 自己根据egon讲的grep命令,类似的道理,写的爬去校花网图片的代码

  

import requests,re,os
def init(f):
def inner(*args,**kwargs):
g=f(*args,**kwargs)
next(g)
return g
return inner
def get(url):
r=requests.get(url)
def inner():
r.encoding='gbk'
return r.text
return inner
xiaohua=get('http://www.xiaohuar.com/2014.html')
xiaohua_contend=xiaohua()
def search(target):
g=re.finditer('<a href=.*? target=.*?><img width=.*? alt="(?P<name>.*?)" src="(?P<src>.*?)" /></a>',xiaohua_contend,re.S)
for i in g:
target.send((i.group('name'),i.group('src')))
@init
def handle(target):
while True:
name,src=yield
if src.startswith('http'):
pass
else:
src='http://www.xiaohuar.com'+src
target.send((name,src))
@init
def download():
while True:
name,src=yield
r=requests.get(src)
with open(r'D:\校花网'+'\\'+name+'.jpg','wb')as f:
f.write(r.content)
search(handle((download())))

总结:

egon授课。

生成器与协程有紧密的联系。

生成器可以通过yield接收参数,通过send传值。

生成器与多线程也有关系吗?没有吧。

普通函数爬取视频也是可以用到多线程的。

优化的余地:可以加上进度条,利用类实现。大概就是这个样式,copy的。

def download_file(url, path):
with closing(requests.get(url, stream=True)) as r:
chunk_size = *
content_size = int(r.headers['content-length'])
print '下载开始'
with open(path, "wb") as f:
p = ProgressData(size = content_size, unit='Kb', block=chunk_size)
for chunk in r.iter_content(chunk_size=chunk_size):
f.write(chunk)
p.output()
class ProgressData(object):

    def __init__(self, block,size, unit, file_name='', ):
self.file_name = file_name
self.block = block/1000.0
self.size = size/1000.0
self.unit = unit
self.count =
self.start = time.time()
def output(self):
self.end = time.time()
self.count +=
speed = self.block/(self.end-self.start) if (self.end-self.start)> else
self.start = time.time()
loaded = self.count*self.block
progress = round(loaded/self.size, )
if loaded >= self.size:
print u'%s下载完成\r\n'%self.file_name
else:
print u'{0}下载进度{1:.2f}{2}/{3:.2f}{4} 下载速度{5:.2%} {6:.2f}{7}/s'.\
format(self.file_name, loaded, self.unit,\
self.size, self.unit, progress, speed, self.unit)
print '%50s'%('/'*int((-progress)*))

day1之校花网小试牛刀的更多相关文章

  1. Python 爬虫 爬校花网!!

    爬虫:是一种按照一定的规则,自动地抓取万维网信息的程序或者脚本 1.福利来了  校花网 ,首先说为什么要爬这个网站呢,第一这个网站简单爬起来容易不会受到打击,第二呢 你懂得... 1.第一步,需要下载 ...

  2. Python-爬取校花网视频(单线程和多线程版本)

    一.参考文章 python爬虫爬取校花网视频,单线程爬取 爬虫----爬取校花网视频,包含多线程版本 上述两篇文章都是对校花网视频的爬取,由于时间相隔很久了,校花网上的一些视频已经不存在了,因此上述文 ...

  3. python爬虫基础应用----爬取校花网视频

    一.爬虫简单介绍 爬虫是什么? 爬虫是首先使用模拟浏览器访问网站获取数据,然后通过解析过滤获得有价值的信息,最后保存到到自己库中的程序. 爬虫程序包括哪些模块? python中的爬虫程序主要包括,re ...

  4. 爬虫(猫眼电影+校花网+github+今日头条+拉钩)

    Requests+正则表达式爬取猫眼TOP100榜电影信息 MARK:将信息写入文件解决乱码方法,开启进程池秒爬. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 ...

  5. Python之爬虫-校花网

    Python之爬虫-校花网 #!/usr/bin/env python # -*- coding:utf-8 -*- import re import requests # 拿到校花网主页的内容 re ...

  6. python实战项目 — 爬取 校花网图片

    重点: 1.  指定路径创建文件夹,判断是否存在 2. 保存图片文件 # 获得校花网的地址,图片的链接 import re import requests import time import os ...

  7. Python 爬虫 校花网

    爬虫:是一种按照一定的规则,自动地抓取万维网信息的程序或者脚本. 福利来了  校花网 ,首先说为什么要爬这个网站呢,第一这个网站简单爬起来容易,不会受到打击,第二呢 你懂得.... 1.第一步,需要下 ...

  8. Go语言实战-爬取校花网图片

    一.目标网站分析 爬取校花网http://www.xiaohuar.com/大学校花所有图片. 经过分析,所有图片分为四个页面,http://www.xiaohuar.com/list-1-0.htm ...

  9. Scrapy爬虫实例——校花网

    学习爬虫有一段时间了,今天使用Scrapy框架将校花网的图片爬取到本地.Scrapy爬虫框架相对于使用requests库进行网页的爬取,拥有更高的性能. Scrapy官方定义:Scrapy是用于抓取网 ...

随机推荐

  1. SnowKiting

    原文 Let's go fly a kite...in the snow Reach into your closet,find that dusty kite and clean it off - ...

  2. php 正则符号说明

    preg_match_all ("/<b>(.*)<\/b>/U", $userinfo, $pat_array); preg_match_all (&qu ...

  3. 最常见的 5 个导致节点重新启动、驱逐或 CRS 意外重启的问题 (文档 ID 1524455.1)

    适用于: Oracle Database - Enterprise Edition - 版本 10.1.0.2 到 11.2.0.3 [发行版 10.1 到 11.2]本文档所含信息适用于所有平台 用 ...

  4. JSONP 跨域请求 - 获取JSON数据

    如何用原生方式使用JSONP? 下边这一DEMO实际上是JSONP的简单表现形式,在客户端声明回调函数之后,客户端通过script标签向服务器跨域请求数据,然后服务端返回相应的数据并动态执行回调函数. ...

  5. HTML5触摸事件

    touchstart .touchmove .touchend 事件 touchstart事件:当手指触摸屏幕时触发,即使有一个手指放在屏幕上也会触发. touchmove事件:当手指在屏幕上滑动时触 ...

  6. CSS盒模型总结(一)

     一.基本概念 盒子模型是css中一个重要的概念,理解了盒子模型才能更好的排版,盒模型的组成:content padding border margin 二.盒模型的分类 盒子模型有两种,分别是 ie ...

  7. Qt读写excel

    今天在利用Qt进行excel操作时,代码总是走到打开excel这一步是总是出现程序崩溃.在网上查找了各种帖子  说法不一,尝试都没有解决.后来猜想是不是excel没有激活影响的.发现自己的excel没 ...

  8. HashMap允许将null用作键 也允许将null作为值

    HashMap不能保证元素的顺序,HashMap能够将键设为null,也可以将值设为null. 与之对应的是Hashtable,(注意大小写:不是HashTable),Hashtable不能将键和值设 ...

  9. Comet OJ 热身赛-principal

    这题的话,我们分析一下,入栈的操作是: 栈空 栈顶元素和当前操作元素不属于同一类括号 栈顶元素和当前操作元素属于同一类括号,但是并不是左括号在前,右括号在后 上面三个条件有任意一个满足都应该入栈,如果 ...

  10. 【php】子类覆盖超类方法,在超类里调用此方法会出现何种现象

    <?php class A { public function getName() { echo $this->name(); } function name () { return 'l ...