• Python的爬虫


      前段时间自学了一段时间的Python,想着浓一点项目来练练手。看着大佬们一说就是爬了100W+的数据就非常的羡慕,不过对于我这种初学者来说,也就爬一爬图片。

      我相信很多人的第一个爬虫程序都是爬去贴吧的图片,嗯,我平时不玩贴吧,加上我觉得豆瓣挺良心的,我就爬了豆瓣首页上面的图片。其实最刚开始是想爬全站,后来一想我这简直是脑子犯抽,全站的图片爬下来得有多少,再说这个只是练一下手,所以就只爬取了首页上的图片。废话不多说 开始代码。

      首先是主文件的代码:

     1 import re
     2 from html_downloder import HtmlDownloader
     3 from html_downloder import Image
     4 
     5 "'起始URL'"
     6 url = "https://www.douban.com"
     7 "'保存目录'"
     8 image_path = "F:sourcePython爬虫ImageGetImage%s.jpg"
     9 "'定义实体类'"
    10 downloader = HtmlDownloader()
    11 html = downloader.download(url)
    12 "'SaveFile(html, html_path)'"
    13 html = html.decode('utf-8')
    14 "'正则表达式'"
    15 reg1 = r'="(https://img[S]*?[jpg|png])"'
    16 "'提取图片的URL'"
    17 dbdata = re.findall(reg1, html)
    18 imgsave = Image()
    19 
    20 "'下载保存图片'"
    21 imgsave.ImageGet(dbdata, image_path)

    我们打开豆瓣首页然后看一下里面图片的url会发现

     

    都是以“=”等号开头,后面接双引号,中间都是https://img,末尾以双引号结束。

    因此我们的正则表达式可以写成 reg1 = r'="(https://img[S]*?[jpg|png])"'

    在这个表达式中"[]"中括号里面的东西会作为一个整体,其中[S]表示大小写字母和数字,[jpg|png]表示以png结尾或者jpg结尾(在这次爬虫中并没有包括gif,因为打开gif的url发现是空白)。

    然后是html_downloder.py的代码:

     1 # file: html_downloader.py
     2 
     3 import urllib.request
     4 import urllib.error
     5 import time
     6 
     7 
     8 class HtmlDownloader(object):
     9     def download(self, url):
    10         if url is None:
    11             return None
    12         try:
    13             header = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64)'}
    14             "'发出请求'"
    15             request = urllib.request.Request(url=url, headers=header)
    16             "'获取结果'"
    17             response = urllib.request.urlopen(url)
    18         except urllib.error.URLError as e:
    19             if hasattr(e, "code"):
    20                 print(e.code)
    21             if hasattr(e, "reason"):
    22                 print(e.reason)
    23         if response.getcode() != 200:
    24             return None
    25         html = response.read()
    26         response.close()
    27         return html
    28 
    29 
    30 class Image (object):
    31     def ImageGet(self, imageurl, image_path):
    32         x = 0
    33         for li in imageurl:
    34             urllib.request.urlretrieve(li, image_path % x)
    35             x = x + 1
    36             "'休眠5s以免给服务器造成严重负担'"
    37             time.sleep(5)

    这个文件的代码主要是负责下载html网页和下载具体的图片。

    接下来就可以在保存路径对应的文件夹中中看到下载的图片了

     至此,爬虫告一段落,离大佬的路还远得很,继续加油!!

  • 相关阅读:
    go并发和并行
    goroutine
    go并发
    wampserver配置问题
    获取字符串的长度
    mysql中事件失效如何解决
    Go语言中Goroutine与线程的区别
    Mosquitto服务器的日志分析
    phpexcel导出数据 出现Formula Error的解决方案
    Centos6.X 手动升级gcc
  • 原文地址:https://www.cnblogs.com/establish/p/8127784.html
Copyright © 2020-2023  润新知