为了加快学习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. Nginx做代理

    0 查看日志 tail -f /var/log/nginx/access.log 1 Nginx代理配置语法 1.Nginx代理配置语法 Syntax: proxy_pass URL; Default ...

  2. js克隆一个对象

    我们知道,对象类型在赋值的过程中其实是复制了地址,所以如果改变了一方,其他都会被改变.我们应该如何克隆一个对象,并且避免这种现象的发生呢? 方法一:Object.assign function cop ...

  3. EVE上传Dynamips、IOL和QEMU镜像

    1.镜像保存目录: /opt/unetlab/addons ---/dynamips   Dynamips镜像保存目录 ---/iol               IOL镜像保存目录(运行IOU的镜像 ...

  4. js函数声明外面使用小括号括起来再接一个小括号的写法

    js函数声明外面使用小括号括起来再接一个小括号的写法 (function(){})(); (function(){}()); !function(){}(); 总结ps:意思将函数声明变成,直接执行的 ...

  5. LeetCode练题——53. Maximum Subarray

    1.题目 53. Maximum Subarray——Easy Given an integer array nums, find the contiguous subarray (containin ...

  6. Java笔记 02-LinkedList

    介绍:List 接口的链接列表实现.实现所有可选的列表操作,并且允许所有元素(包括 null).除了实现 List 接口外,LinkedList 类还为在列表的开头及结尾 get.remove 和 i ...

  7. EasyUI tree的三种选中状态

    EasyUI中tree有三种选中状态,分别是checked(选中).unchecked(未选中).indeterminate(部分选中). 其中indeterminate状态比较特殊,主要表示只有部分 ...

  8. 基于soa的架构

    SOA:Service Oriented Architecture面向服务的架构.也就是把工程拆分成服务层.表现层两个工程.服务层中包含业务逻辑,只需要对外提供服务即可.表现层只需要处理和页面的交互, ...

  9. (转)__attribute__之section 分析详解

    原文地址:__attribute__之section详解 前言 第一次接触 "section" 是在公司的一个STM32的项目代码中,前工程师将所有的初始化函数都使用的" ...

  10. LeetCode简单题(三)

    题目一: 给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格. 如果你最多只允许完成一笔交易(即买入和卖出一支股票),设计一个算法来计算你所能获取的最大利润. 注意你不能在买入股票前卖出股 ...