# 最近在实验楼学习了爬取妹子图,发现在运行的时候不是很流畅,有些图片下 1 # coding: utf-8

 # coding: utf-8

 import re
import threading
from urllib.request import urlopen
from urllib.error import HTTPError
from bs4 import BeautifulSoup
import meizi_series_nextpage def loadurl(url):
try:
conn = urlopen(url)
html = conn.read()
return html
except HTTPError as e:
return e
except Exception as e:
print("unkown exception in conn.read() %s "%e)
return '' def meizi(url,path):
# 获取首页标签
print('start open meiziwang')
html = ''
while True:
html = loadurl(url)
if html == '':
print('load', url,'error')
continue
else:
break
mnvtp = BeautifulSoup(html)
taglists = mnvtp.findAll("div",{"class":"tags"})
taglistss = re.findall('<a.*?href="(.*?)".*?>','%s'%taglists)
print(list(set(taglistss)))
print(len(list(set(taglistss))))
print('open meiziwang over')
meizi_series_nextpage.nextpage(url,path)
threads = []
for url in list(set(taglistss)):
t =threading.Thread(target=meizi_series_nextpage.nextpage, args=(url, path))
threads.append(t)
for t in threads:
t.start()
for t in threads:
t.join()
if __name__ == '__main__':
meizi('http://www.meizitu.com','D:\\MeiZi\\')
print ('Spider Stop')
# coding: utf-8
import re
from urllib.request import urlopen
from urllib.error import HTTPError
from bs4 import BeautifulSoup
import meizi_series_getpage #同样的,这里是加载链接防超时
def loadurl(url):
try:
conn = urlopen(url, timeout=5)
html = conn.read()
return html
except HTTPError as e:
print(e)
except Exception as e:
print(e) def nextpage(url,path):
#获取首页尾部标签
nextweibu = re.split("/",url)
# 获取头部文件
nexthead = re.split("/a/",url)
nexthead = nexthead[0] + "/a/"
# 创建首页路径
path = path+"\\"+nextweibu[-1].split(".",1)[0]
# 获取html
while True:
html = loadurl(url)
if html == '':
print('load', url,'error')
continue
else:
break
# 获取子标签
mnvtp = BeautifulSoup(html)
taglists = mnvtp.findAll("div",{"id":"wp_page_numbers"})
taglists = re.findall('<a.*?href="(.*?)".*?>','%s'%taglists)
taglists = sorted(list(set(taglists)))
if taglists == []:
taglists = [nextweibu[-1]] # 获取单个首页所有标签完整url路径
print("正在获取首页所有子标签Url:%s"%url)
completeurl = []
for i in taglists:
url = nexthead + i
completeurl.append(url)
completeurl = sorted(completeurl)
for i in completeurl:
print("正在获取子标签下所有套图url路径")
meizi_series_getpage.tag_series(i,path)
# coding: utf-8
import time
from urllib.request import urlopen
from urllib.request import Request
from urllib.error import HTTPError
from urllib.request import urlretrieve
import os
import re
from bs4 import BeautifulSoup
import urllib
from urllib import parse
# 图片下载的主逻辑函数,获取图片链接,然后传给pic_list()
def picurl(url,path):
if os.path.exists(path):
print(path,'目录已存在')
else:
print("正在创建目录:%s"%path)
os.makedirs(path)
# 获取套图url(图片)地址
html = ''
while True:
html = loadurl(url)
if html == '':
continue
else:
break
rePicContent1 = '<div.*?id="picture.*?>.*?<p>(.*?)</p>'
rePicContent2 = '<div.*?class="postContent.*?>.*?<p>(.*?)</p>'
rePicList = '<img.*?src="(.*?)".*?>'
#这里对re.S做个介绍,re.S是可以不添加的,加上之后,它的作用就是能忽略换行符,将两条作为一条来匹配。html代码碰上换行的概率是很高的,所以我一致采用re.S(下文有配图)
picContent = re.findall(rePicContent1,"%s"%html,re.S)
if len(picContent) <=0:
picContent = re.findall(rePicContent2, "%s"%html,re.S)
if len(picContent) <=0:
print('无法匹配到对应的图片url')
return False
else:
picList = re.findall(rePicList,"%s"%picContent[0],re.S)
pic_list(picList,path) # #这个函数,相当于一个中介,我只是把for循环代码提出就得到了这个函数
def pic_list(picList,path):
for picurl in picList:
print("获取图片地址:%s"%picurl)
save_pic(picurl,path) #保存图片的逻辑代码块
def save_pic(url,path):
searchname = '.*/(.*?.jpg)'
name = re.findall(searchname,url)
filename = path +'\\'+ name[0] print(filename + ':start') #控制台显示信息 #定义了在下载图片时遇到错误的重试次数
tryTimes = 3 #当重试次数没有用完时,则尝试下载
while tryTimes != 0:
tryTimes -= 1
if os.path.exists(filename):
print(filename,'已存在,跳过')
return True
elif os.path.exists(filename):
os.mknod(filename)
if download(url,filename):
break if tryTimes != 0:
print(filename + ": over")
else:
print(url + " :Failed to download")
#控制台显示信息 #这里是图片保存的代码被调函数,timeout=5设置超时时间,一个500k不到的图片,5秒时间算长的了,超时的话,返回失败 def download(url,filename): try:
headers = {
'Host':'mm.howkuai.com',
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0',
}
Url = Request(url,headers=headers)
req = urlopen(Url).read()
f = open(filename,'wb')
f.write(req)
f.close()
return True
except HTTPError as e:
print(e)
return False
except Exception as e:
print(e) def loadurl(url): try:
conn = urlopen(url,timeout=5)
html = conn.read()
return html
except HTTPError as e:
return ''
except Exception as e:
print("unkown exception in conn.read()")
return ''

有时间在来解释代码含义,第一段代码是主函数,分别根据导入的py创建既可。

Python3网络爬虫的更多相关文章

  1. Python3 网络爬虫(请求库的安装)

    Python3 网络爬虫(请求库的安装) 爬虫可以简单分为几步:抓取页面,分析页面和存储数据 在页面爬取的过程中我们需要模拟浏览器向服务器发送请求,所以需要用到一些python库来实现HTTP的请求操 ...

  2. 崔庆才Python3网络爬虫开发实战电子版书籍分享

    资料下载地址: 链接:https://pan.baidu.com/s/1WV-_XHZvYIedsC1GJ1hOtw 提取码:4o94 <崔庆才Python3网络爬虫开发实战>高清中文版P ...

  3. 《Python3 网络爬虫开发实战》开发环境配置过程中踩过的坑

    <Python3 网络爬虫开发实战>学习资料:https://www.cnblogs.com/waiwai14/p/11698175.html 如何从墙内下载Android Studio: ...

  4. 《Python3 网络爬虫开发实战》学习资料

    <Python3 网络爬虫开发实战> 学习资料 百度网盘:https://pan.baidu.com/s/1PisddjC9e60TXlCFMgVjrQ

  5. Python3网络爬虫开发实战PDF高清完整版免费下载|百度云盘

    百度云盘:Python3网络爬虫开发实战高清完整版免费下载 提取码:d03u 内容简介 本书介绍了如何利用Python 3开发网络爬虫,书中首先介绍了环境配置和基础知识,然后讨论了urllib.req ...

  6. 转:【Python3网络爬虫开发实战】 requests基本用法

    1. 准备工作 在开始之前,请确保已经正确安装好了requests库.如果没有安装,可以参考1.2.1节安装. 2. 实例引入 urllib库中的urlopen()方法实际上是以GET方式请求网页,而 ...

  7. Python3网络爬虫(四):使用User Agent和代理IP隐藏身份《转》

    https://blog.csdn.net/c406495762/article/details/60137956 运行平台:Windows Python版本:Python3.x IDE:Sublim ...

  8. Python3网络爬虫(1):利用urllib进行简单的网页抓取

    1.开发环境 pycharm2017.3.3 python3.5 2.网络爬虫的定义 网络爬虫,也叫网络蜘蛛(web spider),如果把互联网比喻成一个蜘蛛网,spider就是一只在网上爬来爬去的 ...

  9. python3网络爬虫系统学习:第一讲 基本库urllib

    在python3中爬虫常用基本库为urllib以及requests 本文主要描述urllib的相关内容 urllib包含四个模块:requests——模拟发送请求 error——异常处理模块 pars ...

  10. 《Python3网络爬虫开发实战》

    推荐:★ ★ ★ ★ ★ 第1章 开发环境配置 第2章 网页基础知识 第3章 网络爬虫基础 第4章 基本库的使用 第5章 解析库的使用 第6章 数据存储 第7章 Ajax数据爬取 第8章 动态渲染页面 ...

随机推荐

  1. ultraedit中文乱码解决方案

    高级--->配置--->文件处理--->Unicode/UTF-8检测 打钩自动检测UTF-8 文件,去掉其他钩. 来自为知笔记(Wiz)

  2. Google Code Jam 2016 Round 1B Problem C. Technobabble

    题目链接:https://code.google.com/codejam/contest/11254486/dashboard#s=p2 大意是教授的学生每个人在纸条上写一个自己的topic,每个to ...

  3. sass入门学习篇(一)

    先简单的介绍一下sass,如果你了解less,sass就没什么太大问题 Sass 是对 CSS 的扩展,让 CSS 语言更强大.优雅. 它允许你使用变量.嵌套规则. mixins.导入等众多功能, 并 ...

  4. 数据仓库Hive数据导入导出

    Hive库数据导入导出 1.新建表data hive (ebank)> create table data(id int,name string) > ROW FORMAT DELIMIT ...

  5. [ext4]磁盘布局 - group分析

    ext4文件系统的磁盘布局是先把磁盘分成一个个相同大小的block块(每个block块的大小默认是4K),然后把这些block块合成一个个group. group大小最大为256M(默认为256M), ...

  6. 32位机器的LowMemory

        今天在和供应商交流的过程中,被严重鄙视了,竟然认为我连"LowMemory"都没有听说过.感觉很郁闷,好歹我也搞过一段时间memory Management,怎么可能连Lo ...

  7. [内存管理]linux内存管理 之 内存节点和内存分区

    Linux支持多种硬件体系结构,因此Linux必须采用通用的方法来描述内存,以方便对内存进行管理.为此,Linux有了内存节点.内存区.页框的概念,这些概念也是一目了然的. 内存节点:主要依据CPU访 ...

  8. python-day 练习1

    #!/usr/bin/env python# -*- coding:utf-8 -*-'''需求: a. 元素分类 有如下值集合 v1 = [11,22,33,44,55,66,77,88,99,90 ...

  9. Docker - 在Windows7中安装Docker

    安装docker 1 - Virtualization Support Check whether virtualization support is enabled at BIOS via HAV ...

  10. 用户交互式命令:read

    read命令从键盘读取变量的值,通常用在shell脚本中与用户进行交互的场合.该命令可以一次读取多个变量的值,变量和输入的值都需要使用空格隔开. 语法 read [option]... [name . ...