數(shù)據(jù)從何而來
首先我們先知曉該數(shù)據(jù)的接口
image.png
其次,通過代碼去獲取接口數(shù)據(jù)续扔。
ef get_html_data(self, page):
# 實(shí)際請(qǐng)求Url
actual_url = ("https://m.weibo.cn/api/container/getIndex?" +
"type=uid" +
"&value=" + self.user_id +
"&containerid=" + self.domain + self.user_id +
"&page=" + str(page))
# 隨機(jī)獲取headers
res = requests.get(actual_url, headers={'User-Agent': UA[random.randint(0, len(UA) - 1)]}).text
print("抓取開始,第" + str(page) + "次下拉,實(shí)際請(qǐng)求Url:" + actual_url)
return res
user_id #微博用戶ID
containerid #微博默認(rèn)domain+用戶ID
page #頁數(shù)
當(dāng)我們獲取到想要的接口數(shù)據(jù)后,接下來就是需要對(duì)數(shù)據(jù)做數(shù)據(jù)解析评疗。
2.數(shù)據(jù)處理
在剖析數(shù)據(jù)之前测砂,我們需要知道數(shù)據(jù)的結(jié)構(gòu),才能知道采用哪種方式做解析百匆。
我們可以借助工具砌些,可以看到Json的結(jié)構(gòu)。
image.png
知道了數(shù)據(jù)結(jié)構(gòu)后,接下來就是通過代碼去實(shí)現(xiàn)它存璃。
for page in range(1, 10):
res = self.get_html_data(page)
if not res:
print("抓取完成...")
return self.post_list
try:
res_json = json.loads(res)["data"]["cards"]
except Exception:
print("抓取數(shù)據(jù)格式異常B丶觥!纵东!")
return self.post_list
for content in res_json[1:]:
item = {}
# 解析微博數(shù)據(jù)
try:
# 微博賬號(hào)內(nèi)容信息全在這個(gè)標(biāo)簽之后
content = content["mblog"]
# 推文發(fā)布時(shí)間
item["time"] = content["created_at"]
# 推文ID
item["post_id"] = content["id"]
# 推文的BID
item["post_bid"] = content["bid"]
# 推文內(nèi)容
item["text"] = content["text"].replace("\n", ";")
# 推文點(diǎn)贊數(shù)
item["likes"] = content["attitudes_count"]
# 推文評(píng)論數(shù)
item["comments"] = content["comments_count"]
# 推文轉(zhuǎn)發(fā)數(shù)
item["reposts"] = content["reposts_count"]
# 推文是否為轉(zhuǎn)發(fā)
item["if_repost"] = ("retweeted_status" in content)
self.post_list.append(item)
except KeyError:
print("剖析json格式異常")
return self.post_list
time.sleep(2)
4.效果圖
代碼功能完成后粘招,我們可以查看到運(yùn)行結(jié)果。
image.png
image.png
這里你肯定有疑問偎球,那用戶ID從哪拿呢洒扎?
更多源碼信息請(qǐng)參考原文