99999久久久久久亚洲,欧美人与禽猛交狂配,高清日韩av在线影院,一个人在线高清免费观看,啦啦啦在线视频免费观看www

熱線電話:13121318867

登錄
首頁(yè)大數(shù)據(jù)時(shí)代Python抓取知乎幾千張小姐姐圖片是什么體驗(yàn)?
Python抓取知乎幾千張小姐姐圖片是什么體驗(yàn)?
2021-04-01
收藏

來(lái)源:【公眾號(hào)】

Python技術(shù)

知乎上有許多關(guān)于顏值、身材的話題,有些話題的回復(fù)數(shù)甚至高達(dá)幾百上千,擁有成千上萬(wàn)的關(guān)注者與被瀏覽數(shù)。如果我們?cè)诿~(yú)的時(shí)候欣賞這些話題將花費(fèi)大量的時(shí)間,可以用 Python 制作一個(gè)下載知乎回答圖片的小腳本,將圖片下載到本地。

Python抓取知乎幾千張小姐姐圖片是什么體驗(yàn)?

請(qǐng)求 URL 分析

首先打開(kāi) F12 控制臺(tái)面板,看到照片的 URL 都是 https://pic4.zhimg.com/80/xxxx.jpg?source=xxx 這種格式的。

Python抓取知乎幾千張小姐姐圖片是什么體驗(yàn)?

滾動(dòng)知乎頁(yè)面向下翻頁(yè),找到一個(gè)帶 limit,offset 參數(shù)的 URL 請(qǐng)求。

Python抓取知乎幾千張小姐姐圖片是什么體驗(yàn)?

檢查 Response 面板中的內(nèi)容是否包含了圖片的 URL 地址,其中圖片地址 URL 存在 data-original 屬性中。

Python抓取知乎幾千張小姐姐圖片是什么體驗(yàn)?

提取圖片的 URL

從上圖可以看出圖片的地址存放在 content 屬性下的 data-original 屬性中。

下面代碼將獲取圖片的地址,并寫(xiě)入文件。

import re import requests import os import urllib.request import ssl from urllib.parse import urlsplit from os.path import basename import json

ssl._create_default_https_context = ssl._create_unverified_context

headers = {
    'User-Agent'"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36",
    'Accept-Encoding''gzip, deflate' } def get_image_url(qid, title):     answers_url = 'https://www.zhihu.com/api/v4/questions/'+str(qid)+'/answers?include=data%5B*%5D.is_normal%2Cadmin_closed_comment%2Creward_info%2Cis_collapsed%2Cannotation_action%2Cannotation_detail%2Ccollapse_reason%2Cis_sticky%2Ccollapsed_by%2Csuggest_edit%2Ccomment_count%2Ccan_comment%2Ccontent%2Ceditable_content%2Cattachment%2Cvoteup_count%2Creshipment_settings%2Ccomment_permission%2Ccreated_time%2Cupdated_time%2Creview_info%2Crelevant_info%2Cquestion%2Cexcerpt%2Cis_labeled%2Cpaid_info%2Cpaid_info_content%2Crelationship.is_authorized%2Cis_author%2Cvoting%2Cis_thanked%2Cis_nothelp%2Cis_recognized%3Bdata%5B*%5D.mark_infos%5B*%5D.url%3Bdata%5B*%5D.author.follower_count%2Cbadge%5B*%5D.topics%3Bdata%5B*%5D.settings.table_of_content.enabled&offset={}&limit=10&sort_by=default&platform=desktop'     offset = 0     session = requests.Session()

    while True:
        page = session.get(answers_url.format(offset), headers = headers)
        json_text = json.loads(page.text)
        answers = json_text['data']

        offset += 10         if not answers:
            print('獲取圖片地址完成')
            return         pic_re = re.compile('data-original="(.*?)"', re.S)

        for answer in answers:
            tmp_list = []
            pic_urls = re.findall(pic_re, answer['content'])

            for item in pic_urls:  
                # 去掉轉(zhuǎn)移字符                  pic_url = item.replace("""")
                pic_url = pic_url.split('?')[0]

                # 去重復(fù)                 if pic_url not in tmp_list:
                    tmp_list.append(pic_url)

            
            for pic_url in tmp_list:
                if pic_url.endswith('r.jpg'):
                    print(pic_url)
                    write_file(title, pic_url) def write_file(title, pic_url):     file_name = title + '.txt'     f = open(file_name, 'a')
    f.write(pic_url + 'n')
    f.close()

示例結(jié)果:

Python抓取知乎幾千張小姐姐圖片是什么體驗(yàn)?

下載圖片

下面代碼將讀取文件中的圖片地址并下載。

def read_file(title):
    file_name = title + '.txt'     pic_urls = []

    # 判斷文件是否存在
    if not os.path.exists(file_name):
        return pic_urls

    with open(file_name, 'r') as f:
        for line in f:
            url = line.replace("n""")
            if url not in pic_urls:
                pic_urls.append(url)

    print("文件中共有{}個(gè)不重復(fù)的 URL".format(len(pic_urls)))
    return pic_urls

def download_pic(pic_urls, title):

    # 創(chuàng)建文件夾
    if not os.path.exists(title):
        os.makedirs(title)

    error_pic_urls = []
    success_pic_num = 0     repeat_pic_num = 0     index = 1     for url in pic_urls:
        file_name = os.sep.join((title,basename(urlsplit(url)[2])))

        if os.path.exists(file_name):
            print("圖片{}已存在".format(file_name))
            index += 1             repeat_pic_num += 1             continue

        try:
            urllib.request.urlretrieve(url, file_name)
            success_pic_num += 1             index += 1             print("下載{}完成!({}/{})".format(file_name, index, len(pic_urls)))
        except:
            print("下載{}失?。?{}/{})".format(file_name, index, len(pic_urls)))
            error_pic_urls.append(url)
            index += 1             continue
        
    print("圖片全部下載完畢!(成功:{}/重復(fù):{}/失敗:{})".format(success_pic_num, repeat_pic_num, len(error_pic_urls)))

    if len(error_pic_urls) > 0:
        print('下面打印失敗的圖片地址')
        for error_url in error_pic_urls:
            print(error_url)

結(jié)語(yǔ)

今天的文章用 Python 爬蟲(chóng)制作了一個(gè)小腳本,如果小伙伴們覺(jué)得文章有趣且有用,點(diǎn)個(gè) 轉(zhuǎn)發(fā) 支持一下吧!

Python抓取知乎幾千張小姐姐圖片是什么體驗(yàn)?

數(shù)據(jù)分析咨詢請(qǐng)掃描二維碼

若不方便掃碼,搜微信號(hào):CDAshujufenxi

數(shù)據(jù)分析師資訊
更多

OK
客服在線
立即咨詢
客服在線
立即咨詢
') } function initGt() { var handler = function (captchaObj) { captchaObj.appendTo('#captcha'); captchaObj.onReady(function () { $("#wait").hide(); }).onSuccess(function(){ $('.getcheckcode').removeClass('dis'); $('.getcheckcode').trigger('click'); }); window.captchaObj = captchaObj; }; $('#captcha').show(); $.ajax({ url: "/login/gtstart?t=" + (new Date()).getTime(), // 加隨機(jī)數(shù)防止緩存 type: "get", dataType: "json", success: function (data) { $('#text').hide(); $('#wait').show(); // 調(diào)用 initGeetest 進(jìn)行初始化 // 參數(shù)1:配置參數(shù) // 參數(shù)2:回調(diào),回調(diào)的第一個(gè)參數(shù)驗(yàn)證碼對(duì)象,之后可以使用它調(diào)用相應(yīng)的接口 initGeetest({ // 以下 4 個(gè)配置參數(shù)為必須,不能缺少 gt: data.gt, challenge: data.challenge, offline: !data.success, // 表示用戶后臺(tái)檢測(cè)極驗(yàn)服務(wù)器是否宕機(jī) new_captcha: data.new_captcha, // 用于宕機(jī)時(shí)表示是新驗(yàn)證碼的宕機(jī) product: "float", // 產(chǎn)品形式,包括:float,popup width: "280px", https: true // 更多配置參數(shù)說(shuō)明請(qǐng)參見(jiàn):http://docs.geetest.com/install/client/web-front/ }, handler); } }); } function codeCutdown() { if(_wait == 0){ //倒計(jì)時(shí)完成 $(".getcheckcode").removeClass('dis').html("重新獲取"); }else{ $(".getcheckcode").addClass('dis').html("重新獲取("+_wait+"s)"); _wait--; setTimeout(function () { codeCutdown(); },1000); } } function inputValidate(ele,telInput) { var oInput = ele; var inputVal = oInput.val(); var oType = ele.attr('data-type'); var oEtag = $('#etag').val(); var oErr = oInput.closest('.form_box').next('.err_txt'); var empTxt = '請(qǐng)輸入'+oInput.attr('placeholder')+'!'; var errTxt = '請(qǐng)輸入正確的'+oInput.attr('placeholder')+'!'; var pattern; if(inputVal==""){ if(!telInput){ errFun(oErr,empTxt); } return false; }else { switch (oType){ case 'login_mobile': pattern = /^1[3456789]\d{9}$/; if(inputVal.length==11) { $.ajax({ url: '/login/checkmobile', type: "post", dataType: "json", data: { mobile: inputVal, etag: oEtag, page_ur: window.location.href, page_referer: document.referrer }, success: function (data) { } }); } break; case 'login_yzm': pattern = /^\d{6}$/; break; } if(oType=='login_mobile'){ } if(!!validateFun(pattern,inputVal)){ errFun(oErr,'') if(telInput){ $('.getcheckcode').removeClass('dis'); } }else { if(!telInput) { errFun(oErr, errTxt); }else { $('.getcheckcode').addClass('dis'); } return false; } } return true; } function errFun(obj,msg) { obj.html(msg); if(msg==''){ $('.login_submit').removeClass('dis'); }else { $('.login_submit').addClass('dis'); } } function validateFun(pat,val) { return pat.test(val); }