谁能参透 发表于 2024-5-24 11:58:07

【爬虫软件】用Python开发的抖音评论区批量采集工具

一、背景说明

1.1 效果演示

用python开发的爬虫采集软件,可自动抓取抖音评论数据,并且含二级评论!
为什么有了源码还开发界面软件呢?方便不懂编程代码的小白用户使用,无需安装python、无需懂代码,双击打开即用!
软件界面截图:
爬取结果截图:


以上。
1.2 演示视频

软件运行演示视频:见原文
1.3 软件说明

几点重要说明:
二、代码讲解

2.1 爬虫采集模块

首先,定义接口地址作为请求地址:
# 请求地址
url = 'https://www.douyin.com/aweme/v1/web/comment/list/'定义一个请求头,用于伪造浏览器:
# 请求头
h1 = {
        'accept': 'application/json, text/plain, */*',
        'accept-encoding': 'gzip, deflate, br',
        'accept-language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7',
        'cookie': '换成自己的cookie值',
        'referer': 'https://www.douyin.com/',
        'sec-ch-ua': '"Not_A Brand";v="99", "Google Chrome";v="109", "Chromium";v="109"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': '"macOS"',
        'sec-fetch-dest': 'empty',
        'sec-fetch-mode': 'cors',
        'sec-fetch-site': 'same-origin',
        'user-agent': ua,
}其中,cookie是个关键参数,需要填写到软件界面里。cookie获取方法如下:
加上请求参数,告诉程序你的爬取条件是什么:
# 请求参数
params = {
        'device_platform': 'webapp',
        'aid': 6383,
        'channel': 'channel_pc_web',
        'aweme_id': video_id,# 视频id
        'cursor': page * 20,
        'count': 20,
        'item_type': 0,
        'insert_ids': '',
        'rcFT': '',
        'pc_client_type': 1,
        'version_code': '170400',
        'version_name': '17.4.0',
        'cookie_enabled': 'true',
        'screen_width': 1440,
        'screen_height': 900,
        'browser_language': 'zh-CN',
        'browser_platform': 'MacIntel',
        'browser_name': 'Chrome',
        'browser_version': '109.0.0.0',
        'browser_online': 'true',
        'engine_name': 'Blink',
        'engine_version': '109.0.0.0',
        'os_name': 'Mac OS',
        'os_version': '10.15.7',
        'cpu_core_num': 4,
        'device_memory': 8,
        'platform': 'PC',
        'downlink': 1.5,
        'effective_type': '4g',
        'round_trip_time': 150,
        'webid': 7184233910711879229,
        'msToken': 'LZ3nJ12qCwmFPM1NgmgYAz73RHVG_5ytxc_EMHr_3Mnc9CxfayXlm2kbvRaaisoAdLjRVPdLx5UDrc0snb5UDyQVRdGpd3qHgk64gLh6Tb6lR16WG7VHZQ==',
}下面就是发送请求和接收数据:
# 请求地址
url = 'https://www.douyin.com/aweme/v1/web/comment/list/'# 发送请求r = requests.get(url, headers=h1, params=params)# 转json格式json_data = r.json()定义一些空列表,用于存放解析后字段数据:
ip_list = []# ip属地
text_list = []# 评论内容
create_time_list = []# 评论时间
user_name_list = []# 评论者昵称
user_url_list = []# 评论者主页链接
user_unique_id_list = []# 评论者抖音号
like_count_list = []# 点赞数
cmt_level_list = []# 评论级别循环解析字段数据,以"评论内容"为例:
# 循环解析
for comment in comment_list:
        # 评论内容
        text = comment['text']
        text_list.append(text)其他字段同理,不再赘述。
最后,是把数据保存到csv文件:
# 保存数据到DF
df = pd.DataFrame(
        {
                '目标链接': 'https://www.douyin.com/video/' + str(video_id),
                '页码': page,
                '评论者昵称': user_name_list,
                '评论者id': user_unique_id_list,
                '评论者主页链接': user_url_list,
                '评论时间': create_time_list,
                '评论IP属地': ip_list,
                '评论点赞数': like_count_list,
                '评论级别': cmt_level_list,
                '评论内容': text_list,
        }
)
# 保存到csv文件
if os.path.exists(result_file):# 如果文件存在,不再设置表头
        header = False
else:# 否则,设置csv文件表头
        header = True
df.to_csv(result_file, mode='a+', index=False, header=header, encoding='utf_8_sig')完整代码中,还含有:判断循环结束条件、时间戳转换、二级评论及二级展开评论的采集等关键实现逻辑,详见文末。
2.2 软件界面模块

软件界面采用tkinter开发。
主窗口部分:
# 创建日志目录
work_path = os.getcwd()
if not os.path.exists(work_path + "/logs"):
        os.makedirs(work_path + "/logs")
# 创建主窗口
root = tk.Tk()
root.title('抖音评论采集软件 | 马哥python说')
# 设置窗口大小
root.minsize(width=850, height=650)填写cookie控件:
# 【填入Cookie】
tk.Label(root, justify='left', font=('微软', 14), text='个人Cookie:').place(x=30, y=75)
entry_ck = tk.Text(root, bg='#ffffff', width=110, height=2, )
entry_ck.place(x=30, y=100, anchor='nw')# 摆放位置填写视频链接控件:
# 【视频链接】
tk.Label(root, justify='left', font=('微软', 14), text='视频链接:').place(x=30, y=145)
note_ids = tk.StringVar()
note_ids.set('')
entry_nt = tk.Text(root, bg='#ffffff', width=110, height=14, )
entry_nt.place(x=30, y=170, anchor='nw')# 摆放位置底部软件版权说明:
# 版权信息
copyright = tk.Label(root, text='@马哥python说 All rights reserved.', font=('仿宋', 10), fg='grey')
copyright.place(x=290, y=625)以上。
2.3 日志模块

好的日志功能,方便软件运行出问题后快速定位原因,修复bug。
核心代码:
def get_logger(self):
        self.logger = logging.getLogger(__name__)
        # 日志格式
        formatter = '[%(asctime)s-%(filename)s][%(funcName)s-%(lineno)d]--%(message)s'
        # 日志级别
        self.logger.setLevel(logging.DEBUG)
        # 控制台日志
        sh = logging.StreamHandler()
        log_formatter = logging.Formatter(formatter, datefmt='%Y-%m-%d %H:%M:%S')
        # info日志文件名
        info_file_name = time.strftime("%Y-%m-%d") + '.log'
        case_dir = r'./logs/'
        info_handler = TimedRotatingFileHandler(filename=case_dir + info_file_name,
                                                                                        when='MIDNIGHT',
                                                                                        interval=1,
                                                                                        backupCount=7,
                                                                                        encoding='utf-8')日志文件截图:
三、转载声明

转载已获原作者 @马哥python说授权:
博客园原文链接:【GUI界面软件】抖音评论采集:自动采集10000多条,含二级评论、展开评论!
持续分享Python干货中,欢迎交流开发技术!

来源:https://www.cnblogs.com/ws235/p/18210398
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!
页: [1]
查看完整版本: 【爬虫软件】用Python开发的抖音评论区批量采集工具