吾爱破解 - 52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 3830|回复: 24
收起左侧

[Python 转载] 使用Python微博图片爬取保存

  [复制链接]
初梦立春 发表于 2020-7-21 22:41
本帖最后由 初梦立春 于 2020-7-22 09:23 编辑

第一次发帖,学习python爬虫中。
[Asm] 纯文本查看 复制代码
# -*- coding: utf-8 -*-
import urllib.request
import json
import requests
import os

path = 'D:\\weibo'

#id = '[url=tel:2093492691]2093492691[/url]'这里决定爬取人的ID
id = '[url=tel:6049590367]6049590367[/url]'
proxy_addr = "122.241.72.191:808"
pic_num = 0
weibo_name = "programmer"


def use_proxy(url, proxy_addr):
    req = urllib.request.Request(url)
    req.add_header("User-Agent",
                   "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.221 Safari/537.36 SE 2.X MetaSr 1.0")
    proxy = urllib.request.ProxyHandler({'http': proxy_addr})
    opener = urllib.request.build_opener(proxy, urllib.request.HTTPHandler)
    urllib.request.install_opener(opener)
    data = urllib.request.urlopen(req).read().decode('utf-8', 'ignore')
    return data


def get_containerid(url):
    data = use_proxy(url, proxy_addr)
    content = json.loads(data).get('data')
    for data in content.get('tabsInfo').get('tabs'):
        if (data.get('tab_type') == 'weibo'):
            containerid = data.get('containerid')
    return containerid


def get_userInfo(id):
    url = 'https://m.weibo.cn/api/container/getIndex?type=uid&value=' + id
    data = use_proxy(url, proxy_addr)
    content = json.loads(data).get('data')
    profile_image_url = content.get('userInfo').get('profile_image_url')
    description = content.get('userInfo').get('description')
    profile_url = content.get('userInfo').get('profile_url')
    verified = content.get('userInfo').get('verified')
    guanzhu = content.get('userInfo').get('follow_count')
    name = content.get('userInfo').get('screen_name')
    fensi = content.get('userInfo').get('followers_count')
    gender = content.get('userInfo').get('gender')
    urank = content.get('userInfo').get('urank')
    print("微博昵称:" + name + "\n" + "微博主页地址:" + profile_url + "\n" + "微博头像地址:" + profile_image_url + "\n" + "是否认证:" + str(
        verified) + "\n" + "微博说明:" + description + "\n" + "关注人数:" + str(guanzhu) + "\n" + "粉丝数:" + str(
        fensi) + "\n" + "性别:" + gender + "\n" + "微博等级:" + str(urank) + "\n")


def get_weibo(id, file):
    global pic_num
    i = 1
    while True:
        url = 'https://m.weibo.cn/api/container/getIndex?type=uid&value=' + id
        weibo_url = 'https://m.weibo.cn/api/container/getIndex?type=uid&value=' + id + '&containerid=' + get_containerid(
            url) + '&page=' + str(i)
        try:
            data = use_proxy(weibo_url, proxy_addr)
            content = json.loads(data).get('data')
            cards = content.get('cards')
            if (len(cards) > 0):
                for j in range(len(cards)):
                    print("-----正在爬取第" + str(i) + "页,第" + str(j) + "条微博------")
                    card_type = cards[j].get('card_type')
                    if (card_type == 9):
                        mblog = cards[j].get('mblog')
                        attitudes_count = mblog.get('attitudes_count')
                        comments_count = mblog.get('comments_count')
                        created_at = mblog.get('created_at')
                        reposts_count = mblog.get('reposts_count')
                        scheme = cards[j].get('scheme')
                        text = mblog.get('text')
                        if mblog.get('pics') != None:
                            # print(mblog.get('original_pic'))
                            # print(mblog.get('pics'))
                            pic_archive = mblog.get('pics')
                            for _ in range(len(pic_archive)):
                                pic_num += 1
                                print(pic_archive[_]['large']['url'])
                                imgurl = pic_archive[_]['large']['url']
                                img = requests.get(imgurl)
                                f = open(path + weibo_name + '\\' + str(pic_num) + str(imgurl[-4:]),
                                         'ab')  # 存储图片,多媒体文件需要参数b(二进制文件)
                                f.write(img.content)  # 多媒体存储content
                                f.close()

                        with open(file, 'a', encoding='utf-8') as fh:
                            fh.write("----第" + str(i) + "页,第" + str(j) + "条微博----" + "\n")
                            fh.write("微博地址:" + str(scheme) + "\n" + "发布时间:" + str(
                                created_at) + "\n" + "微博内容:" + text + "\n" + "点赞数:" + str(
                                attitudes_count) + "\n" + "评论数:" + str(comments_count) + "\n" + "转发数:" + str(
                                reposts_count) + "\n")
                i += 1
            else:
                break
        except Exception as e:
            print(e)
            pass


if __name__ == "__main__":
    if os.path.isdir(path + weibo_name):
        pass
    else:
        os.mkdir(path + weibo_name)
    file = path + weibo_name + '\\' + weibo_name + ".txt"
    get_userInfo(id)
    get_weibo(id, file)

免费评分

参与人数 2吾爱币 +2 热心值 +1 收起 理由
带御器械 + 1 + 1 谢谢@Thanks!
清晴请庆 + 1 用心讨论,共获提升!

查看全部评分

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

带御器械 发表于 2021-1-24 21:01
Traceback (most recent call last):
  File "D:/python_test/mypro_obj/wb.py", line 111, in <module>
    get_userInfo(id)
  File "D:/python_test/mypro_obj/wb.py", line 40, in get_userInfo
    profile_image_url = content.get('userInfo').get('profile_image_url')
AttributeError: 'NoneType' object has no attribute 'get'
请问这个错误是什么意思呢?
ysnsn 发表于 2020-7-22 07:04
邪恶的左手 发表于 2020-7-22 07:19
dreamocean 发表于 2020-7-22 07:39
可以的 不错楼主,最近也是刚学习Python,看一下
觅寻 发表于 2020-7-22 07:41
学习学习
yinchangsheng58 发表于 2020-7-22 07:42
牛逼大佬。但是爬虫太难了
dht592117 发表于 2020-7-22 07:47
同样是学python爬虫的,为啥你这么厉害,点赞
Kirin992 发表于 2020-7-22 07:50
阔以阔以,涨知识了
当初遇你时 发表于 2020-7-22 08:10
谢谢分享
代达罗斯之殇 发表于 2020-7-22 08:42
可以可以,不知道能不能出个爬知乎回答图片的
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则

返回列表

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2024-11-25 19:46

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表