Python版本 3.6

简单写一个爬虫,在写的过程熟悉Python语法,不得不说Python用起来真666;

  代码功能是访问网站首页将所有a标签值作为文件夹,将当前网页所有图片下载对应文件夹中;其实还有很多很多需要修改和完善的地方 比如异常,多线程,递归等;以后有机会再说吧.欢迎拍砖

 1 # -*- UTF-8 -*-
2 from urllib import request
3 from bs4 import BeautifulSoup
4 import os
5 import time, threading
6
7
8 exe_Count = 1
9 aList = []
10
11 def CallView(url, timeout, directoryPath,exe_count):
12 try:
13 listAvalue = []
14 headers = {
15 "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 UBrowser/6.1.2716.5 Safari/537.36",
16 "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"
17 }
18 rep = request.Request(url, headers=headers)
19 response = request.urlopen(rep, timeout=timeout)
20 soup = BeautifulSoup(response)
21 # 获取a标签href 属性并写入list
22 for a in soup.find_all("a"):
23 if a.string is None:
24 continue
25 if not a.attrs["href"].strip() in aList:
26 aList.append(a.attrs["href"].strip())
27 listAvalue.append([a.string.strip()[0:11], a.attrs["href"].strip()])
28 else:
29 continue
30 # 创建不存在的目录
31 if not os.path.exists(directoryPath):
32 os.mkdir(directoryPath)
33 print("新目录:" + directoryPath)
34 # 开启线程递归
35 thread = threading.Thread(target=ForRequest, args=(listAvalue, timeout, directoryPath,exe_count))
36 thread.start()
37 listImgSrc = []
38 # 获取img标签 并下载
39 for img in soup.find_all("img"):
40 try:
41 imgSrc = img.attrs["src"]
42 print(imgSrc)
43 # 过滤重复src
44 if not imgSrc in listImgSrc:
45 listImgSrc.append(imgSrc)
46 # 读取图片
47 rep = request.Request(imgSrc)
48 response = request.urlopen(rep, timeout=timeout)
49 # 写入图片
50 filepath = directoryPath + "/" + imgSrc.split('/')[len(imgSrc.split('/')) - 1]
51 with open(filepath, "wb") as o:
52 o.write(response.read())
53 except:
54 print("访问图片或者写入本地Error")
55 except request.HTTPError as e:
56 print(e.code)
57 except:
58 print("CallView Error")
59
60
61 def ForRequest(listA, timeout, directoryPath,exe_count):
62 print("当前已执行:" + str(exe_count) + " 次")
63 #调用次数超过200跳出
64 if exe_count == 2:
65 thread = threading.current_thread()
66 raise SystemError("正在停止线程")
67 else:
68 exe_count = exe_count + 1
69
70 for info in listA:
71 directoryChildPath = directoryPath + "/" + info[0]
72 if not os.path.exists(directoryChildPath):
73 os.mkdir(directoryChildPath)
74 CallView(info[1], timeout, directoryChildPath, exe_count)
75
76 try:
77 print("爬虫开始活动了")
78 CallView("http://www.xxxxx.com", 5000, "D:/PythonTest/Img/素材公社",exe_Count);
79 print("爬虫正在偷偷活动,不要着急哦!")
80 except:
81 print("Error")

最新文章

  1. netstat命令
  2. scikit-learn的梯度提升算法(Gradient Boosting)使用
  3. SpringMVC学习--文件上传
  4. 重新想象 Windows 8 Store Apps (44) - 多线程之异步编程: 经典和最新的异步编程模型, IAsyncInfo 与 Task 相互转换
  5. MVC-生成验证码
  6. UML图中类之间的关系:依赖,泛化,关联,聚合,组合,实现
  7. EXT系统中的信息查询
  8. 如何在嵌入式Linux上开发一个语音通信解决方案
  9. CSS属性:定位属性(图文详解)
  10. 一次完整的HTTP网络请求过程详解
  11. openlayers4 入门开发系列之地图空间查询篇(附源码下载)
  12. laravel——ajax分页&删除&搜索
  13. 《推荐》安装Photoshop详细步骤 ,手把手,一步一步,具体详细地教你安装Photoshop (Adobe photoshop CS6)
  14. js 手写 Promise
  15. Spring 实现两种设计模式:工厂模式和单态模式(单例模式)
  16. php write_ini_file
  17. spoj MINSUB 单调栈+二分
  18. 数据库:XML,解析Dom4J
  19. InstallShield程序打包图解
  20. Kubernetes-Service Account

热门文章

  1. Grafana 系列文章(八):Grafana Explore 中的 Inspector
  2. .Net7运行模型之托管Main函数的调用
  3. Stats collector is not responding 统计信息收集器没有响应
  4. JAVA基础知识-String.format
  5. Istio 升级后踩的坑
  6. Java 集合中的排序算法浅析
  7. dataset的基本使用
  8. Golang HTTP编程及源码解析
  9. js原型链污染详解
  10. Vue学习:实现用户没有登陆时,访问后自动跳转登录页面