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

  

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. 提取循环中包含continue的语句封装成方法

    demo如下: private void button1_Click(object sender, EventArgs e) { ;i<;i++) { if (!a(i)) { continue ...

  2. this+call、apply、bind的区别与使用

    http://www.ruanyifeng.com/blog/2018/06/javascript-this.html https://segmentfault.com/a/1190000018017 ...

  3. Open Cascade:拓扑类型(Topo_DS)之间类型转换

    TopoDS_Edge aEdge = TopoDS::Edge(myAISShape->Shape()); TopoDS_Wire S1_wire = static_cast(S1); // ...

  4. js 两个数组对象根据账号比较去重,解决直接splice后数组索引改变

    目的获取Arr2中不包含在arr1中的对象 根据Account进行比较,如果相等则删除tempArr数组对象. 结果返回张三 var arr1=[{"account":" ...

  5. PHP的PDF扩展库TCPDF将中文字体设置为内嵌字体的方法

    1. 下载要设置的字体,如名为simfang.ttf,放在./vendor/tecnickcom/tcpdf/tools目录中 2.在tools目录中按住shift,点击鼠标右键,点击“在此处打开命令 ...

  6. common-fileupload上传文件

    文件上传在web应用中非常普遍,要在jsp环境中实现文件上传功能是非常容易的,因为网上有许多用java开发的文件上传组件,本文以commons-fileupload组件为例,为jsp应用添加文件上传功 ...

  7. UIScreen, UIWindow

    模仿书上或网上的例子,每次最开始就是 在 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions: ...

  8. ios开发--常用的高效开发的宏

    本次在做项目的时候使用了下面的一些宏定义 以及 建立宏定义的一些规则.虽然只用了其中的一点点,但是还是极大的提高了开发效率.. 将这些宏放到一个头文件里然后再放到工程中,在需要使用这些宏定义的地方体检 ...

  9. UIViewAnimationOptions

    常规动画属性设置(可以同时选择多个进行设置) UIViewAnimationOptionLayoutSubviews:执行UIView动画时,自动更新Subview的Layout约束.. UIView ...

  10. 简单css动画 fadeIn fadeOut flash

    考虑兼容性采用 -webkit- -o- -mos- -ms- @keyframes fadeIn{ 0%{ opacity: 0; display: block; } 100%{ opacity: ...