python爬取图虫网图片

网站:https://stock.tuchong.com/

打开调试工具发现如下关键代码
如上图
代码:

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; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36')
    response=urllib.request.urlopen(url)
    html=response.read()
    return html

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

    #print(html)
    
    a= html.find('hotTopic')+31
    b= html.find(',',a)
    #print(html[a:b])
    return html[a:b] 

def find_image(url):
    html = url_open(url).decode('utf-8')
    #print(html)
    image_address = []

    a=html.find('imageId')
    #print(a)
    while a!=-1:
        b= html.find('title',a,a+255)
        #print("b:",b)
        if b!=-1:
            image_address.append('//weiliicimg9.pstatp.com/weili/sm/'+html[a+10:b-3]+'.webp')
        else:
            b=a+10
        a=html.find('imageId',b)
    return image_address
    #print(image_address)
def save_image(folder,image_address):
    for each in image_address:
        filename = each.split('/')[-1]

        with open(filename,'wb') as f:
            img=url_open('https:'+each)
            f.write(img)
            
def download_mm(folder='lianxi',pages=10):
    os.mkdir(folder)
    os.chdir(folder)

    url="https://stock.tuchong.com/"

    # page_num = get_page(url)
    random_str=int(get_page_index(url))

    for i in range(pages):
        
        random_str-=1
        print(random_str)
        page_url=url+'topic?topicId='+str(random_str)
        print(page_url)
        image_address=find_image(page_url)
        save_image(folder,image_address)
    


if __name__ =='__main__':
    download_mm()

喜欢的朋友可以试试!!!

你可能感兴趣的:(个人笔记)