python3爬虫爬取煎蛋网妹纸图片(下篇)2018.6.25有效

分析完了真实图片链接地址,下面要做的就是写代码去实现了。

大致思路是:获取一个页面的的html---->使用正则表达式提取出图片hash值并进行base64解码--->将解码得到的结果进行拼接替换,得到原始图片地址--->对图片地址进行请求,对返回的content进行保存--->扩展到多个页面的爬取

首先请求一个页面,我们以http://jandan.net/ooxx/page-47#comments也就是首页为例(网站会不时变动,下次可能就不是这个page值了)

def get_page_html(url):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36'
    }
    try:
        response = requests.get(url, headers=headers)
        if response.status_code == 200:
            return response.text
        return None
    except Exception as e:
        print(e)

然后使用正则表达式提取图片hash值

def get_real_img(html):
    pattern = re.compile('<span class="img-hash">(.*?)</span>')
    imgs_hash = re.findall(pattern, html)
    for img_hash in imgs_hash:
        yield base64_decode(img_hash)

使用base64解码

def base64_decode(img_hash):
    img_hash = base64.b64decode(img_hash)
    return img_hash

对图片进行请求

def get_img_content(url):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36'
    }
    try:
        response = requests.get(url, headers=headers)
        if response.status_code == 200:
            save_img(url, response.content)
        return None
    except Exception as e:
        print(e)

对图片进行保存

def save_img(url, content):
    root = 'E://jandan/'
    path = root + url.split('/')[-1]
    if not os.path.exists(root):
        os.mkdir(root)
    if not os.path.exists(path):
        with open(path, 'wb') as f:
            f.write(content)
            print('保存成功', url)

定义一个主函数,这里我传入了一个参数i,也就是页面号。另外加了一个睡眠,在每一次对页面进行请求获取内容前停留一段时间,防止频繁爬取被封ip。

def main(i):
    start_url = 'http://jandan.net/ooxx/page-{}#comments'.format(i)
    time.sleep(random.random() * random.randint(1, 10))
    html = get_page_html(start_url)
    for result in get_real_img(html):
        url_split = result.decode('utf-8').split('/')
        real_img_url = 'http://{}/{}/{}'.format(url_split[-3], 'large', url_split[-1])
        get_img_content(real_img_url)

最后写一个程序入口:

if __name__ == '__main__':
    start_page = 1
    end_page = 47
    pool = Pool()
    pool.map(main, [i for i in range(start_page, end_page + 1)])

最后的最后我们看一下成果:

好了,关于煎蛋的话题就到这里。

猜你喜欢

转载自www.cnblogs.com/sjfeng1987/p/9223226.html