python入门学习笔记之爬虫二

实现不了,先记录

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/83.0.4103.116 Safari/537.36')  # 添加文件头
    response = urllib.request.urlopen(url)    # 访问
    html = response.read()

    return html


def get_page(url):
    html = url_open(url).decode('utf-8')

    a = html.find('NO.46249') + 9  # 偏移,9
    b = html.find('<', a)

    return html[a:b]


def find_imgs(url):
    html = url_open(url).decode('utf-8')
    img_addrs = []

    a = html.find('img src=')
    b = html.find('.jpg', a, a+255)

    while a != -1:
        if b != -1:
            img_addrs.append('http:' + html[a+9:b+4])
        else:
            b = a + 9

        a = html.find('img src=', b)

    return img_addrs


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


def download_mm(folder='OOXX', pages=10):
    os.mkdir(folder)   # 创建文件夹
    os.chdir(folder)   # 切换进去

    url = "http://jandan.net/t/"
    page_num = int(get_page(url))

    for i in range(pages):
        page_num -= i
        page_url = url + '46294' + str(page_num)
        imgs_addrs = find_imgs(page_url)
        save_imgs(folder, imgs_addrs)


if __name__ == '__main__':
    download_mm()

你可能感兴趣的:(python,python)