为了加快学习python3.x,查了许多资料后写了这个脚本,这个脚本主要是爬取百度图片'东方幻想乡'的图片,但还是有很多问题存在。

  下面给出代码:

# 更新了一下代码
from urllib import request
import re class CrawlImg: # 定义一个爬取图片的类
def __init__(self): # 构造函数
print('Link start!') def __GetHtml(self, html):
post = request.urlopen(html)
page = post.read()
return page.decode('utf-8') # 将格式转换为utf-8格式 TypeError: cannot use a string pattern on a bytes-like object def __GetImg(self, html):
page = self.__GetHtml(html) # 获取 html 页面
recomp = re.compile(r'.+?.jpg')  #新的、简洁的正则表达式
imgUrlList = recomp.findall(page) # 和 html 页面正则匹配
return imgUrlList # 返回匹配得到的 jpg 的 url 列表 def run(self, html):
imgUrlList = self.__GetImg(html)
ImgName = 1
fp = open('C:\\Users\\adimin\\Desktop\\CrawlImg\\imgUrl.txt', 'w')
for imgUrl in imgUrlList:
request.urlretrieve(imgUrl, 'C:\\Users\\adimin\\Desktop\\CrawlImg\\{}.jpg' .format(str(ImgName)))
print('Download:', imgUrl)
fp.write(str(imgUrl) + '\r\n')
ImgName += 1
fp.close() def __del__(self): # 析构函数
print("Download finished!") def main():
url = 'https://image.baidu.com/search/index?tn=baiduimage&ct=201326592&lm=-1&cl=2&ie=gbk&word=%B6%AB%B7%BD%BB%C3%CF%EB%CF%E7&fr=ala&ala=1&alatpl=adress&pos=0&hs=2&xthttps=111111'
GetImg = CrawlImg()
GetImg.run(url) if __name__ == '__main__':
main()

  参考了许多博客和资料,主要有:

http://blog.csdn.net/clj198606061111/article/details/50816115
https://www.cnblogs.com/speeding/p/5097790.html
http://urllib3.readthedocs.io/en/latest/
https://pyopenssl.org/en/stable/
https://docs.python.org/3.6/library/urllib.html
https://segmentfault.com/q/1010000004442233/a-1020000004448440
http://urllib3.readthedocs.io/en/latest/user-guide.html
菜鸟教程-python3

  还有一些记不得了...

  然后,通过这次的学习学到了很多,基本熟悉了python3的基本语法,还了解了正则表达式的写法等,于是用了面向对象的方式进行编程。

  代码中可以看到:一个爬取图片的类,构造函数、析构函数等。

  还有另一个版本的url请求,用了urllib3.PoolManager():

# 修改了一下代码,现在能正常运行了
from urllib import request
import urllib3
import certifi
import re class CrawlImg: # 定义一个爬取图片的类
def __init__(self): # 构造函数
print('Link start!') def __GetHtml(self, html):
post = urllib3.PoolManager(  # 初始化,为了解决一个证书问题,还安装了 pyOpenSSL,但没有用...最后,这样写就解决了InsecureRequestWarning的警告
cert_reqs='CERT_REQUIRED',
ca_certs=certifi.where()
)
post = post.request('GET', html)  # 请求打开网页
page = post.data  # 读取页面数据
return page.decode('utf-8') # 将格式转换为utf-8格式 TypeError: cannot use a string pattern on a bytes-like object def __GetImg(self, html):
page = self.__GetHtml(html) # 获取 html 页面数据
recomp = re.compile(r'.+?.jpg')  # 更新
imgUrlList = recomp.findall(page) # 和 html 页面正则匹配
return imgUrlList # 返回匹配得到的 jpg 的 url 列表 def run(self, html):
imgUrlList = self.__GetImg(html)
ImgName = 1
fp = open('C:\\Users\\adimin\\Desktop\\CrawlImg\\imgUrl.txt', 'w')
for imgUrl in imgUrlList:
request.urlretrieve(imgUrl, 'C:\\Users\\adimin\\Desktop\\CrawlImg\\{}.jpg' .format(str(ImgName)))
print('Download:', imgUrl)
fp.write(str(imgUrl) + '\r\n')
ImgName += 1
fp.close() def __del__(self): # 析构函数
print("Download finished!") def main():
url = 'https://image.baidu.com/search/index?tn=baiduimage&ct=201326592&lm=-1&cl=2&ie=gbk&word=%B6%AB%B7%BD%BB%C3%CF%EB%CF%E7&fr=ala&ala=1&alatpl=adress&pos=0&hs=2&xthttps=111111'
GetImg = CrawlImg()
GetImg.run(url) if __name__ == '__main__':
main()

  最后,感觉没什么好解释的地方,这篇就总结到这了。

-----------------update 2018-01-19 22:56:43----------------

  最近发现别人的正则表达式都比叫简单...我的都好长...但不太明白这个表达式是怎么匹配的:

import re
url = 'https://i.pximg.net/user-profile/img/2017/07/03/10/55/30/12797398_1982f9bf699bd2ff2b67855b276bbb8c_50.png'
recmp = re.compile(r'.+?.jpg|.+?.png')
print(recmp.findall(url))

  ps:后来弄明白了。

Python学习 —— 实现简单的爬虫的更多相关文章

  1. 使用python做最简单的爬虫

    使用python做最简单的爬虫 --之心 #第一种方法import urllib2 #将urllib2库引用进来response=urllib2.urlopen("http://www.ba ...

  2. Python 学习(1) 简单的小爬虫

    最近抽空学了两天的Python,基础知识都看完了,正好想申请个联通日租卡,就花了2小时写了个小爬虫,爬一下联通日租卡的申请页面,看有没有好记一点的手机号~   人工挑眼都挑花了. 用的IDE是PyCh ...

  3. python学习总结----简单数据结构

    mini-web服务器 - 能够完成简单的请求处理 - 使用http协议 - 目的:加深对网络编程的认识.为后面阶段学习web做铺垫 简单数据结构 - 排列组合 import itertools # ...

  4. Python学习笔记:利用爬虫自动保存图片

    兴趣才是第一生产驱动力. Part 1 起先,源于对某些网站图片浏览只能一张一张的翻页,心生不满.某夜,冒出一个想法,为什么我不能利用爬虫技术把想看的图片给爬下来,然后在本地看个够. 由此经过一番初尝 ...

  5. python学习:简单的wc命令实现

    #!/usr/bin/python   import sys import os   try:     fn = sys.argv[1] except IndexError:     print &q ...

  6. python学习 —— python3简单使用pymysql包操作数据库

    python3只支持pymysql(cpython >= 2.6 or >= 3.3,mysql >= 4.1),python2支持mysqldb. 两个例子: import pym ...

  7. Python写一个简单的爬虫

    code #!/usr/bin/env python # -*- coding: utf-8 -*- import requests from lxml import etree class Main ...

  8. python学习之----初见网络爬虫(输出整个网页html的代码)

    from urllib import urlopen html = urlopen('http://www.manluotuo.com') print (html.read()) 控制台输出整个网页h ...

  9. Python学习-一个简单的计时器

    在实际开发中,往往想要计算一段代码执行多长时间,以下我将该功能写入到一个函数里面,仅仅要在每一个函数前面调用该函数就可以,见以下代码: #------------------------------- ...

随机推荐

  1. DIV 设置垂直居中

    要说面试官经常问的问题中“如何将一个块元素水平垂直居中”就算一个. 之前的面试中也有中招,现在总结一下. 1.CSS垂直水平居中 要让DIV水平和垂直居中,必需知道该DIV得宽度和高度,然后设置位置为 ...

  2. 为什么要使用wsgi协议

    一个cs模型是由服务器和客户端组成,大多相互情况下也就是服务器端和浏览器之间的通信.通过浏览器请求服务器,然后服务器再响应浏览器. 那么如果浏览器想要请求一个python文件,例如http://127 ...

  3. 苗条的生成树 Slim Span--洛谷

    传送门 钢哥终于没给黑题紫题了(卑微v 稍稍需要多想一点点 ---------------------------------------------------------------------- ...

  4. 多进程pipe

    pipe模块可以实现进程之间数据传递 栗子1:3个进程,一个主进程,2个子进程,三个管道,三个进程通过3个管道连接,主进程发一个信息,通过2个子进程转发,最后回到主进程输出 import multip ...

  5. Laravel Vuejs 实战:开发知乎 (6)发布问题

    1.view部分: 安装一个扩展包:Laravel-UEditor composer require "overtrue/laravel-ueditor:~1.0" 配置 添加下面 ...

  6. 学习笔记(26)- plato-端到端模型-定闹钟

    今天用了定闹钟的场景语料,在plato框架尝试了端到端的模型. 本文先记录英文的训练过程,然后记录中文的训练过程. 训练端到端的模型 发现使用英文的模型,还是显示有中文,所以,新建目录,重新训练 1. ...

  7. IDEA启动报错-java.net.BindException: Address already in use: bind

    启动IDEA报错日志如下: Internal error. Please refer to http://jb.gg/ide/critical-startup-errors java.net.Bind ...

  8. python linux windows 历史版本下载

    Index of /ftp/python/ ../ 2.0/ 14-Feb-2019 14:53 - 2.0.1/ 06-Aug-2001 02:14 - 2.1/ 06-Aug-2001 02:14 ...

  9. MongoDB - 运行

    运行 mongod --dbpath (mongod is the "Mongo Daemon") 在shell用mongo或者用studio 3t可视化连接 创建用户 db.cr ...

  10. vscode安装过的插件

    1.VSCode的Vue插件Vetur设置,alt+shift+f格式化 对应配置 今天看到的文章安装插件可以参考: https://blog.csdn.net/maixiaochai/article ...