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

  

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. Vue+webpack+echarts+jQuery=demo

    需要的插件: "dependencies": { "bootstrap": "^3.3.7", "echarts": & ...

  2. table 会有默认的外边框,内部会有分割线

    .表格中边框的显示 只显示上边框 <table frame=above> 只显示下边框 <table frame=below> 只显示左.右边框 <table frame ...

  3. 安装vc++6.0的步骤

    我们学习计算机,就必须要先将编程的c语言学好,打好基础,学习c语言最好的方法就是多上机联系,对于联系我们需要在自己的电脑上安装vc++6.0来进行平日里的联系.1.打开电脑进行联网,打开浏览器搜索vc ...

  4. VS2019 KEY

    VS2019正式版 密钥 Visual Studio 2019 破解 激活码 Key   Visual Studio 2019 Enterprise 企业版(亲测可用):BF8Y8-GN2QH-T84 ...

  5. viewDidLoad、loadView

    一.loadView永远不要主动调用这个函数.view controller会在view的property被请求并且当前view值为nil时调用这个函数.如果你手动创建view,你应该重载这个函数,且 ...

  6. ios retain copy 以及copy协议

    阅读本文之前首先了解Copy与Retain的区别: Copy是创建一个新对象,Retain是创建一个指针,引用对象计数加1. Copy属性表示两个对象内容相同,新的对象retain为1 ,与旧有对象的 ...

  7. java获取本地计算机MAC地址

    java获取本地计算机MAC地址代码如下: public class SocketMac { //将读取的计算机MAC地址字节转化为字符串 public static String transByte ...

  8. python 基础知识汇总—— if else while continue

    1.if 语句 什么是if语句?if语句用来干什么的? if语句说通俗点,就是判断,如果判断条件为真,那么就执行语句,就像我们生活中例子,如果你饿了,判断为真,就要吃饭,于是你就会执行吃饭这个动作,如 ...

  9. django第8天(在测试文件中运行django项目|单表操作)

    django第8天 在测试文件中运行django项目 1.将项目配置文件数据库该为mysql,修改配置信息 PORT = '127.0.0.1' DATABASES = { 'default': { ...

  10. 数据结构( Pyhon 语言描述 ) — —第10章:树

    树的概览 树是层级式的集合 树中最顶端的节点叫做根 个或多个后继(子节点). 没有子节点的节点叫做叶子节点 拥有子节点的节点叫做内部节点 ,其子节点位于层级1,依次类推.一个空树的层级为 -1 树的术 ...