为了加快学习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. 如何用纯代码实现图片CSS3

    在刷面试题的时候刷到2015阿里巴巴的,如何用代码实现下面的图形. <div class="main"> <h1>图片图标-一个标签实现</h1> ...

  2. easyExcel+poi导出Excel出现乱码

    这种问题肯定是浏览器编码问题,修改官方给的util就好了

  3. National Contest for Private Universities (NCPU), 2019 C Boxes(双向链表)

    题目中的要求如果x在y的左边,不需要移动,x在y的右边,2操作不需要移动. 有一个问题是,如果x与y相邻,这时的swap操作变成了三个而不是四个,这点尤其需要注意,不然就会死循环.注意x是和y相邻,这 ...

  4. nginx 解决 connect() failed (111: Connection refused) while connecting to upstream,

    嗯哼,刚装了个ubuntu的lnmp,我的天啊,踩的坑比我脂肪还多了 比如刚装完的时候访问显示502, 也不知道什么问题,就去看了一下nginx日志  /var/log/nginx/error.log ...

  5. 《实战Java高并发程序设计》读书笔记四

    第四章 锁的优化及注意事项 1.锁性能的几点建议 减小锁持有时间: 系统持有锁时间越长锁竞争程度就越激烈,只对需要同步的方法加锁,可以减小锁持有时间进而提高锁性能. 减少锁的持有时间有助于降低锁冲突的 ...

  6. 2020牛客寒假算法基础集训营3 - G. 牛牛的Link Power II(线段树)

    题目链接:牛牛的Link Power II 题意:给你一个只含$0$和$1$的串,定义串的$Link$值为串中两个的$1$之间的距离的和,$(u,v)$和$(v,u)$被看认为是同一对,有$m$次操作 ...

  7. pc和手机点击复制到剪贴板

    https://www.cnblogs.com/kevinCoder/p/6144376.html

  8. python中for循环中的循环变量

    废话不多说,代码伺候: for i in range(3): print("hello") print(i) 运行结果如下: 从上面的例子可以看出,for循环里面的循环变量i作用域 ...

  9. C语言:求n(n<10000)以内的所有四叶玫瑰数。-将字符串s1和s2合并形成新的字符串s3,先取出1的第一个字符放入3,再取出2的第一个字符放入3,

    //函数fun功能:求n(n<10000)以内的所有四叶玫瑰数并逐个存放到result所指数组中,个数作为返回值.如果一个4位整数等于其各个位数字的4次方之和,则称该数为函数返回值. #incl ...

  10. Vacuum Pump Manufacturer - Vacuum Pump: Prevents Reactive Compound Decomposition Products

    Vacuum packaging has been popular in the industry for a long time. Many large companies have joined ...