为了加快学习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. java 倒入一篇文章,显示每个字母的出现概率,从大到小排序

    package com_1; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; ...

  2. win10安装 .net3.5失败解决方法

    #开始 最近需要学习Sql Server 但是发现SQL Server2008r2 版本的安装程序基于.net 电脑没有安装.net3.5 #解决过程 可笑的是我在用离线安装包安装.net3.5的时候 ...

  3. 吴裕雄 python 机器学习——模型选择数据集切分

    import numpy as np from sklearn.model_selection import train_test_split,KFold,StratifiedKFold,LeaveO ...

  4. Python学习第二十八课——Django(templates)

    templates 讲后台得到的数据渲染到页面上:话不多说,先看具体代码. urls: from django.conf.urls import url from django.contrib imp ...

  5. 【C语言】找出1000以内所有的素数

    #include<stdio.h> int main() { int i, j, t; ; i <= ; i++) { ; ; j < i; j++) { ) { t = ; ...

  6. docker-install-v0.1-alpha

    Written by Zak Zhu docker-install-v0.1-alpha/ ├── inventory ├── roles │ └── docker │ ├── defaults │

  7. [linux] ARCH LINUX 常见问题及实用工具汇总

    1.办公 screen-recorder 1)深度linux桌面录制软件(不支持录音),操作简单,可以保存mp4和gif格式 2)命令安装:sudo pacman -S deepin-screen-r ...

  8. JPA中实现双向多对多的关联关系(附代码下载)

    场景 JPA入门简介与搭建HelloWorld(附代码下载): https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/103473937 ...

  9. 带有“全选”的combotree

    <div id="setBtn_dd" class="easyui-window" data-options="iconCls:'icon-sa ...

  10. /var/lib/gems/2.5.0/gems/seccomp-tools-1.3.0/lib/seccomp-tools/dumper.rb:125: warning: Insecure world writable dir /home/python/.local in PATH, mode 040777 解决方案

    /var/lib/gems/2.5.0/gems/seccomp-tools-1.3.0/lib/seccomp-tools/dumper.rb:125: warning: Insecure worl ...