zoukankan      html  css  js  c++  java
  • Python学习 —— 实现简单的爬虫

      为了加快学习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) + '
    ')
                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) + '
    ')
                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:后来弄明白了。

     

  • 相关阅读:
    设计模式---行为变化模式之命令模式(Command)
    设计模式---数据结构模式之职责链模式(Chain of Responsibility)
    设计模式---数据结构模式之迭代器模式(Iterate)
    WinCE全屏手写输入法
    .net下所有DLL(API)查询,转换C#代码
    在线cron表达式生成器
    完全卸载vs2013、vs2015的方法
    java微信 客服接口-发消息 中文乱码
    【路由达人】简单两步搞定小米路由新增功能-DDNS(解析域名地址转向在线工具)
    微信公众平台开发入门教程
  • 原文地址:https://www.cnblogs.com/darkchii/p/8214949.html
Copyright © 2011-2022 走看看