python学习笔记之模块爬虫实战-爬取网站图片(十四)

背景说明

爬取煎蛋网中随手拍栏目中的某页的所有图片

实战

分析

  1. 先打开煎蛋网站中的“随手拍”,链接为:http://jandan.net/ooxx/MjAyMDA1MTctMTc1#comments
  2. 按F12打开开发者工具,然后在图片上点击“检查”,可看到图片的链接
  3. 找到这些图片的链接,然后保存即可

代码实现

  1. download_images方法创建保存图片的文件夹,再调用find_images找到图片的地址,再用save_imgs方法来保存图片
  2. url_open方法说明:很多地方都要从链接请求html文件,所以封装了
  3. find_images方法说明:在html文件中查找图片链接地址

代码示例如下:

import urllib.request
import os

def url_open(url):
    req = urllib.request.Request(url)
    req.add_header('User-Agent','Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36')
    response = urllib.request.urlopen(req)
    html = response.read()
    return html
    
def find_images(url):
    html = url_open(url).decode('utf-8')
    img_addrs = []
    a = html.find('img src=')
    print('a:'+str(a))
    while a != -1:
        b = html.find('.jpg',a,a+255)
        print('b:'+str(b))
        if b != -1:
            img_addrs.append(html[a+9:b+4])
        else:
            b = a + 9

        a = html.find('img src=',b)
    for each in img_addrs:
        print(each)
    return img_addrs

def save_imgs(folder,img_addrs):
    for each in img_addrs:
        print('save_imgs_each:'+each)
        filename = each.split('/')[-1]
        with open(filename,'wb') as f:
            img = url_open('http:'+each)
            f.write(img)


def download_images(url):
    print(url)
    folder='images'
    os.mkdir(folder)
    os.chdir(folder)
    page_num = int(get_page(url))
    img_addrs = find_images(url)
    save_imgs(folder,img_addrs)

if __name__ == '__main__':
    url = 'http://jandan.net/ooxx/MjAyMDA1MTctMTc1#comments'
    download_images(url)

github上的代码

你可能感兴趣的:(python)