用 Python 下載好看的米哈游 coser 小姐姐
↑?關(guān)注 + 星標(biāo)?,每天學(xué)Python新技能
后臺回復(fù)【大禮包】送你Python自學(xué)大禮包
文 |?某某白米飯
來源:Python 技術(shù)「ID: pythonall」

米哈游不僅有原神,還有 coser 小姐姐和 coser 女裝大佬,上班的時候用 python 爬蟲偷偷下載,加班的時候摸摸魚,謹防猝死。

防爬蟲
打開米哈游的 coser 界面 https://bbs.mihoyo.com/dby/topicDetail/547,并且在打開 F12 控制面板的時候,刷新頁面。意外的是居然有 js 的防爬蟲機制,表現(xiàn)為如下圖:

js 代碼是
(function?anonymous()?{
debugger
})
點擊下面的倒數(shù)第二個按鈕,破解掉它。

列表頁
想要快速找到返回頁面內(nèi)容的 url 地址,可以在網(wǎng)絡(luò)面板中使用 Ctrl+F 查找,然后對呀返回值一條條查看是否是需要的那條,這里找到了一條 getTopicPostList 地址的 url。

這個頁面是沒有翻頁的,對比第二頁的 getTopicPostList 請求地址,比第一個多了 last_id 參數(shù),最終的參數(shù)為:
gids: 5,未知 last_id: 18114983,最后一個的 id is_good: false,未知 is_hot: false,是否熱門 page_size: 20,每頁條數(shù) forum_id: 47,板塊 id sort_type: 排序
import?requests
import?time
headers?=?{
????????"User-Agent":?"Mozilla/5.0?(Windows?NT?10.0;?Win64;?x64)?AppleWebKit/537.36?(KHTML,?like?Gecko)?Chrome/98.0.4758.102?Safari/537.36",
????????"Origin":?"https://bbs.mihoyo.com",
????????"Referer":?"https://bbs.mihoyo.com/",
????????"Host":?"bbs-api.mihoyo.com"
????}
def?request_get(url,?ret_type):
????res?=?requests.get(url=url,?headers=headers,?timeout=5)
????res.encoding?=?"utf-8"
????if?ret_type?==?"text":
????????return?res.text
????elif?ret_type?==?"image":
????????return?res.content
????elif?ret_type?==?"json":
????????return?res.json()
def?main(last_id):
????url?=?f'https://bbs-api.mihoyo.com/post/wapi/getForumPostList?forum_id=47&gids=5&is_good=false&is_hot=false&last_id={last_id}&page_size=20&sort_type=2'
????res_json?=?request_get(url,?"json")
????if?res_json["retcode"]?==?0:
????????for?item?in?res_json["data"]["list"]:
????????????post_id?=?item["post"]["post_id"]
????????????detail(post_id)
????????????????
????if?res_json["data"]["last_id"]?!=?"":
????????return?main(res_json["data"]["last_id"])
詳細頁
詳細的 url 地址也是返回的 json 串,而且只需要傳遞 post_id 參數(shù)就好了,比較簡單。圖片的 url 地址就在 ["data"]["post"]["image_list"] 下,在返回的圖片中有違規(guī)的圖片,需要提前處理下。
def?detail(post_id):
????url?=?f"https://bbs-api.mihoyo.com/post/wapi/getPostFull?gids=5&post_id={post_id}&read=1"
????res_json?=?request_get(url,?"json")
????if?res_json["retcode"]?==?0:
????????image_list?=?res_json["data"]["post"]["image_list"]
????????for?img?in?image_list:
????????????img_url?=?img["url"]
????????????if?(img_url.find("weigui"))?0:
????????????????save_image(img_url)
保存圖片
保存圖片就是普通的 with open 函數(shù)和文件的 write 函數(shù)。
def?save_image(image_src):
????r?=?requests.get(image_src)
????content?=?r.content
????name?=?image_src.split('/')[-1]
????with?open('D://mhy//'?+?name,?"wb")?as?f:
????????f.write(content)

總結(jié)
這篇文章的技術(shù)就使用了 requests 和 json 以及一點點的控制面板反爬蟲。小伙伴們學(xué)會了嗎?
推薦閱讀
您看此文用? ?
?分?
?
秒,轉(zhuǎn)發(fā)只需1秒哦
評論
圖片
表情

?
?分?
?
秒,轉(zhuǎn)發(fā)只需1秒哦