博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python爬虫爬取煎蛋网妹子图片
阅读量:6828 次
发布时间:2019-06-26

本文共 1955 字,大约阅读时间需要 6 分钟。

import urllib.requestimport osdef url_open(url):    req = urllib.request.Request(url)    req.add_header("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:54.0) Gecko/20100101 Firefox/54.0")    response = urllib.request.urlopen(url)    html = response.read()    return html    def get_page(url):    html = url_open(url).decode("utf-8")    a = html.find("current-comment-page") + 23    b = html.find(']',a)    return html[a:b]def find_imgs(page_url):    html = url_open(page_url).decode("utf-8")    img_addrs = []    a = html.find("img src=")        while a!=-1:        b = html.find(".jpg",a,a+255)        if b!=-1:            img_addrs.append(html[a+9:b+4])        else:            b = a+9        a = html.find("img src",b)    return img_addrsdef save_imgs(folder,img_addrs):    for each in img_addrs:        filename = each.split('/')[-1]        with open(filename,'wb') as f:            each = "http:"+each            img = url_open(each)            f.write(img)            def download_mm(folder="mm",pages=10):    os.mkdir(folder)    os.chdir(folder)    url = "http://jandan.net/ooxx/"    page_num = int(get_page(url))    for i in range(pages):        page_num -= i        page_url = url + 'page-' + str(page_num) + "#comments"        img_addrs = find_imgs(page_url)        save_imgs(folder,img_addrs)download_mm()

将url_open函数修改,使用代理会出错:

def url_open(url):    req = urllib.request.Request(url)    req.add_header("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:54.0) Gecko/20100101 Firefox/54.0")        proxies = ['221.237.122.22:8118','171.37.192.220:8123','110.73.0.59:8123','171.39.4.208:8123']    proxy = random.choice(proxies)    proxy_support = urllib.request.ProxyHandler({
'http':proxy}) opener = urllib.request.build_opener(proxy_support) urllib.request.install_opener(opener) response = urllib.request.urlopen(url) html = response.read() return html

 

转载于:https://www.cnblogs.com/ncuhwxiong/p/7216103.html

你可能感兴趣的文章