Python爬虫 - 抓取Tiktok小视频

前言

好久没更新了,更新一下
不废话了

正文

确保电脑安装了 charles / fiddler / wireshark 或其他能抓包的工具,然后在手机或者模拟器上配置好代理,记得安装证书,接着开始抓包。

:最好在 Android7.0 以下配置,7.0及以上版本不能抓https了,有点麻烦,推荐使用模拟器

首先安装好 tiktok ,打开后翻几个视频,会发现抓包工具里出现一堆请求
charles
我们需要找到它小视频请求的链接,经过我个把小时的分析,找到了这个
charles
接下来需要模拟请求,看看他的请求头

accept-encoding = gzip
user-agent = okhttp/3.10.0.1
method = GET

接着我发现虽然是GET请求,但是url链接后面有一串贼鸡儿长的参数,wtm。。。
好吧,分析分析请求参数把,看着太费劲所以我写了一个解析方法,解析成json格式,如下
 "type": "0",
 "max_cursor": "0",
 "min_cursor": "-1",
 "count": COUNT, # 加载个数
 "volume": "0.2",
 "pull_type": "2",
 "req_from": "",
 "gaid": "",
 "ad_user_agent": "Dalvik%2F2.1.0+%28Linux%3B+U%3B+Android+6.0.1%3B+MuMu+Build%2FV417IR%29", # 广告ua
 "filter_warn": "0",
 "ts": TIMESTAMP[:-3], # 时间戳
 "js_sdk_version": "",
 "app_type": "normal",
 "os_api": "28",
 "device_type": "Xiaomi",
 "ssmix": "a",
 "manifest_version_code": "9999",
 "dpi": "240",
 "carrier_region": "JP", # 获取的小视频来源
 "region": "JP",
 "carrier_region_v2": "",
 "app_name": "trill",
 "version_name": "4.2.4",
 "ab_version": "4.2.4",
 "timezone_offset": "28800",
 "pass-route": "1",
 "pass-region": "1",
 "is_my_cn": "0",
 "fp":"",
 #"fp": "R2TrcrUtFMsrFYQZcrU1LSFeFWm1",
 "ac": "wifi",
 "update_version_code": "4240",
 "channel": "googleplay",
 "_rticket": TIMESTAMP, # 时间戳(保留毫秒)
 "device_platform": "android",
 "iid":"6678981313393919746", # 暂不知来源,必须有,不能更改
#     "iid": "6678981313393919746",
 "build_number": "9.5",
 "version_code": "424",
 "timezone_name": "Asia%2FShanghai",
 "openudid": "c55cd951e5464a56",
 "device_id": "6678979145927919106",
 "sys_region": "JP",
 "app_language": "zh-Hans",
 "resolution": RESOLUTION, # 画质
#     "resolution": "1280*720",
 "os_version": "9",
 "device_brand": "Android",
 "language": "jp",
 "aid": "1180", # 暂不知来源,必须有,不能更改
 "mcc_mnc": "",
 "as": "",
 "cp":"",
 "mas":""
 #"as": "a10548abb2087cfbe04299",
 #"cp": "8c8fc35c2606b9bae1Wc_g",
 #"mas": "019e07c3ae4fc3d6e172de9de34998f0ae9c9c4c2c0ca64666c6ec"
}
这里面有些能从字面意思看懂的就不多说了,主要看那后面几个,fp、iid、aid、as、cp、mas 这里除了iid和aid这两个参数不能更改以外,以他的参数随便改,暂时也不知道 ​ 和 ​ 这两个参数的来历,保持不变即可
ok,模拟请求,代码如下
import requests
​
headers = {
 "User-Agent": "okhttp/3.10.0.1",
 "Accpet-Encoding": "gzip"
}
​
url = "https://api-h2.tiktokv.com/aweme/v1/feed/"
​
def parse_url_params(param):
 """
 解析url参数为json
 """
 params = {}
 if '?' in param:
 p = param.split('?')[-1]
 ps = p.split('&')
 for i in ps:
 a = i.split('=')
 params.update({a[0]:'' if len(a) == 1 else a[1]})
 else:
 ps = param.split('&')
 for i in ps:
 a = i.split('=')
 params.update({a[0]:'' if len(a) == 1 else a[1]})
 return params
​
params = parse_url_params("type=0&max_cursor=0&min_cursor=-1&count=6&volume=0.2&pull_type=2&req_from&gaid&ad_user_agent=Dalvik%2F2.1.0+%28Linux%3B+U%3B+Android+6.0.1%3B+MuMu+Build%2FV417IR%29&filter_warn=0&ts=1555073922&js_sdk_version=&app_type=normal&os_api=23&device_type=MuMu&ssmix=a&manifest_version_code=9999&dpi=240&carrier_region=JP®ion=CN&carrier_region_v2=&app_name=trill&version_name=4.2.4&ab_version=4.2.4&timezone_offset=28800&pass-route=1&pass-region=1&is_my_cn=0&fp=R2TrcrUtFMsrFYQZcrU1LSFeFWm1&ac=wifi&update_version_code=4240&channel=googleplay&_rticket=1555073923091&device_platform=android&iid=6678981313393919746&build_number=9.5&version_code=424&timezone_name=Asia%2FShanghai&openudid=c55cd951e5464a56&device_id=6678979145927919106&sys_region=CN&app_language=zh-Hans&resolution=1280*720&os_version=6.0.1&device_brand=Android&language=zh&aid=1180&mcc_mnc=&as=a10548abb2087cfbe04299&cp=8c8fc35c2606b9bae1Wc_g&mas=019e07c3ae4fc3d6e172de9de34998f0ae9c9c4c2c0ca64666c6ec")
​
resp = requests.get(url, headers=headers, params=params)
print(resp.json())
输出一堆json内容,由于内容实在是太多,所以只看重点部分,下面是几个
{'aweme_id': '6673431479185624322', 'desc': '', 'create_time': 1553847851,..., 'video': {'play_addr': {'uri': 'v07025860000bietc60src5j25b1epvg', 'url_list': [...], ... 'play_addr': {'uri': 'v07025860000bietc60src5j25b1epvg', 'url_list': [...], ... , 'url_list': [...], ... , 'url_list': [...] ... 'url_list': [...], 'width': 720, 'height': 720, 'url_key': 'v07025860000bietc60src5j25b1epvg_h264_360p_290447'}, 'is_h265': 0}], ...}
这是一个视频的部分json内容,我们需要的有 create_timevideo - play_addr - uri,emmm好像就这些,还有作者的信息我没有贴上来自行分析吧,接着上全部代码
# Spider.py
import sys
import requests
​
from config import * # 这里我把请求参数写在config里了,代码在下面
​
​
class TiktokSpider:
​
 def __init__(self):
 self.url = 'https://api-h2.tiktokv.com/aweme/v1/feed'
 self.headers = {
 "User-Agent": "okhttp/3.10.0.1",
 "Accpet-Encoding": "gzip"
 }
​
 def get_aweme_list(self):
 """
 获取视频列表
 :return:
 """
 resp = requests.get(self.url, headers=self.headers, params=PARAMS)
 if resp.status_code != requests.codes.OK:
 print("获取视频列表失败.")
 return None
 try:
 return resp.json()['aweme_list']
 except KeyError:
 print(resp.text)
​
 def parse_video(self):
 """
 解析json格式小视频列表数据
 :return:
 """
 aweme_list = self.get_aweme_list()
 if aweme_list is None:
 return aweme_list
 video_result = []
 for aweme in aweme_list:
 play_addr = aweme['video']['play_addr']
 author = aweme['author']
 result = {
 'video_infos': {
 'url': play_addr['url_list'],
 'width': play_addr['width'],
 'height': play_addr['height'],
 'description': aweme['desc'],
 'create_time': str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(aweme['create_time']))),
 },
 'aweme_id': aweme['aweme_id'],
 'avatar_infos': {
 'url': author['avatar_thumb']['url_list'],
 'height': author['avatar_larger']['height'],
 'width': author['avatar_larger']['width']
 },
 'author_infos': {
 'nickname': author['nickname'],
 'uid': author['uid'],
 'short_id': author['short_id'],
 'signature': author['signature'],
 }
​
 }
 video_result.append(result)
 return video_result
​```
```python
# config.py
import time
import math
​
ORIGION='JP'
COUNT="10"
TIMESTAMP=str(math.floor(time.time()*1000))
RESOLUTION="1920*1080"
​
​
PARAMS = {
 "type": "0",
 "max_cursor": "0",
 "min_cursor": "-1",
 "count": COUNT, # 加载个数
 "volume": "0.2",
 "pull_type": "2",
 "req_from": "",
 "gaid": "",
 "ad_user_agent": "Dalvik%2F2.1.0+%28Linux%3B+U%3B+Android+6.0.1%3B+MuMu+Build%2FV417IR%29", # 广告ua
 "filter_warn": "0",
 "ts": TIMESTAMP[:-3], # 时间戳
 "js_sdk_version": "",
 "app_type": "normal",
 "os_api": "28",
 "device_type": "Xiaomi",
 "ssmix": "a",
 "manifest_version_code": "9999",
 "dpi": "240",
 "carrier_region": "JP", # 获取的小视频来源
 "region": "JP",
 "carrier_region_v2": "",
 "app_name": "trill",
 "version_name": "4.2.4",
 "ab_version": "4.2.4",
 "timezone_offset": "28800",
 "pass-route": "1",
 "pass-region": "1",
 "is_my_cn": "0",
 "fp":"",
 #"fp": "R2TrcrUtFMsrFYQZcrU1LSFeFWm1",
 "ac": "wifi",
 "update_version_code": "4240",
 "channel": "googleplay",
 "_rticket": TIMESTAMP, # 时间戳(保留毫秒)
 "device_platform": "android",
 "iid":"6678981313393919746", # 暂不知来源,必须有,不能更改
#     "iid": "6678981313393919746",
 "build_number": "9.5",
 "version_code": "424",
 "timezone_name": "Asia%2FShanghai", # 时区
 "openudid": "c55cd951e5464a56",
 "device_id": "6678979145927919106",
 "sys_region": "JP", 
 "app_language": "zh-Hans",
 "resolution": RESOLUTION, # 画质
#     "resolution": "1280*720",
 "os_version": "9",
 "device_brand": "Android",
 "language": "jp",
 "aid": "1180", # 暂不知来源,必须有,不能更改
 "mcc_mnc": "",
 "as": "",
 "cp":"",
 "mas":""
 #"as": "a10548abb2087cfbe04299",
 #"cp": "8c8fc35c2606b9bae1Wc_g",
 #"mas": "019e07c3ae4fc3d6e172de9de34998f0ae9c9c4c2c0ca64666c6ec"
}

最后

emmm,其实我把抓到的数据用flask写成了一个小网站,由于我css贼垃圾,所以做的不是很美观,项目地址: Flask-Tiktok

原文:Python爬虫 - 抓取国际版tiktok小视频

你可能感兴趣的:(Python爬虫 - 抓取Tiktok小视频)