# requirement.txt
jieba==0.38
matplotlib==2.0.2
numpy==1.13.1
pyparsing==2.2.0
requests==2.18.4
scipy==0.19.1
wordcloud==1.3.1
pip install -r requirement.txt第一步:分析网址
uid=1192515960&再来分析接口的返回结果,返回数据是一个JSON字典结构,total 是微博总条数,每一条具体的微博内容封装在 cards 数组中,具体内容字段是里面的 text 字段。很多干扰信息已隐去。
luicode=10000011&
lfid=100103type%3D3%26q%3D%E6%9D%8E%E5%86%B0%E5%86%B0&
featurecode=20000320&
type=user&
containerid=1076031192515960
{第二步:构建请求头和查询参数
"cardlistInfo": {
"containerid": "1076031192515960",
"total": 4754,
"page": 2
},
"cards": [
{
"card_type": 9,
"mblog": {
"created_at": "08-26",
"idstr": "4145069944506080",
"text": "瑞士一日游圆满结束...",
}
}]
}
headers = {
"Host": "m.weibo.cn",
"Referer": "[url=https://m.weibo.cn/u/1705822647%22]https://m.weibo.cn/u/1705822647"[/url],
"User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) "
"Version/9.0 Mobile/13B143 Safari/601.1",
}
params = {"uid": "{uid}",
"luicode": "20000174",
"featurecode": "20000320",
"type": "uid",
"value": "1705822647",
"containerid": "{containerid}",
"page": "{page}"}
def fetch_data(uid=None, container_id=None):
"""
抓取数据,并保存到CSV文件中
:return:
"""
page = 0
total = 4754
blogs =
for i in range(0, total // 10):
params['uid'] = uid
params['page'] = str(page)
params['containerid'] = container_id
res = requests.get(url, params=params, headers=HEADERS)
cards = res.json().get("cards")
for card in cards:
# 每条微博的正文内容
if card.get("card_type") == 9:
text = card.get("mblog").get("text")
text = clean_html(text)
blogs.append(text)
page += 1
print("抓取第{page}页,目前总共抓取了 {count} 条微博".format(page=page, count=len(blogs)))
with codecs.open('weibo1.txt', 'w', encoding='utf-8') as f:
f.write("\n".join(blogs))
def generate_image():最终效果图:
data =
jieba.analyse.set_stop_words("./stopwords.txt")
with codecs.open("weibo1.txt", 'r', encoding="utf-8") as f:
for text in f.readlines():
data.extend(jieba.analyse.extract_tags(text, topK=20))
data = " ".join(data)
mask_img = imread('./52f90c9a5131c.jpg', flatten=True)
wordcloud = WordCloud(
font_path='msyh.ttc',
background_color='white',
mask=mask_img
).generate(data)
plt.imshow(wordcloud.recolor(color_func=grey_color_func, random_state=3),
interpolation="bilinear")
plt.axis('off')
plt.savefig('./heart2.jpg', dpi=1600)
作者:刘志军
本文为 @ 21CTO 创作并授权 21CTO 发布,未经许可,请勿转载。
内容授权事宜请您联系 webmaster@21cto.com或关注 21CTO 公众号。
该文观点仅代表作者本人,21CTO 平台仅提供信息存储空间服务。