线程池抓取

import datetime
import json
import warnings

from jsonpath import jsonpath
from sqlalchemy.exc import ResourceClosedError

warnings.filterwarnings('ignore')
import random
import time

import requests
import pandas as pd
import records
from urllib import parse
import traceback
from pymysql.converters import escape_string
from sqlalchemy import create_engine
from fake_useragent import UserAgent
from concurrent.futures import ThreadPoolExecutor, as_completed
from collections import deque

# from my_proxies import proxy


"""
1.到douyin_account_all表 获取main_page字段内容
2.根据main_page 内容拼接url
3.发请求
4.解析数据
5.存储数据
"""
proxy = [
   
    {'http://': 'http://192.168.241.62:9976',
     'https://': 'https://192.168.241.62:9976'},

]


class CrawlAima:
    def __init__(self):
        self.ua = UserAgent()
        self.db = records.Database(
            f"mysql+pymysql://user:{parse.quote_plus('abc')}@0.0.0.0:3306/db?charset=utf8mb4")
        self.conn = create_engine(self.db.db_url)

        self.dq = deque()
        self.counter = {} # sec_id 记录失败次数
        self.url = 'https://www.iesdouyin.com/post/'

        self.get_time_by_vid_list = []
        self.video_sql = self.get_video_sql()
        self.vid_dict = self.get_all_video()
        # 获取所有main_page
        # self.get_main_page()

    def get_all_video(self):
        vid_dict = self.db.query("select video_id,post_time from douyin_video_extend_main").as_dict()
        return {i['video_id']: str(i['post_time']) for i in vid_dict}


    def get_video_sql(self):
        video_sql = """
                        INSERT INTO douyin_video_extend_main (
                        video_id,
                        userid,
                        comment_num,
                        like_num,
                        collect_num,
                        share_num,
                        url,
                        content,
                        cover_pic,
                        post_time
                        )
                        VALUES
                        (
                        :video_id,
                        :userid,
                        :comment_num,
                        :like_num,
                        :collect_num,
                        :share_num,
                        :url,
                        :content,
                        :cover_pic,
                        :post_time
                        )
                        ON DUPLICATE KEY UPDATE
                            video_id = :video_id,
                            userid = :userid,
                            comment_num = :comment_num,
                            like_num = :like_num,
                            collect_num = :collect_num,
                            share_num = :share_num,
                            url = :url,
                            content = :content,
                            cover_pic = :cover_pic
                        """
        return video_sql

    def get_main_page(self):
        main_page = self.db.query("select userid, main_page,open_id from douyin_account_all;")

        df = main_page.export("df")
        df = df.dropna(subset=['main_page'])
        self.main_page_list = []
        if not df.empty:
            df.main_page = df.main_page.map(lambda x: x.rsplit('/', 1)[-1])
            self.main_page_list = df.main_page.to_list()
            self.main_page_dict = {v: k+1 for k, v in enumerate(self.main_page_list)}
            # 获取用户userid
            self.userid_list = df.userid.to_list()
            self.userid_dict = {str(u): 1 for u in self.userid_list}

            # {userid:open_id}
            df['userid'] = df['userid'].astype('str')
            self.uid_oid_map = dict(zip(df['userid'].to_list(),df['open_id'].to_list()))


    def counter_sec_uid(self,sec_uid):
        # sec_uid 记录次数
        if self.counter.get(sec_uid):
            self.counter[sec_uid] += 1
        else:
            self.counter[sec_uid] = 1

    def crawl_handler(self, sec_uid, max_cursor=0):
        params = {
            "sec_uid": sec_uid,
            "max_cursor": max_cursor,
            "count": 21,
            "key": "188"
        }
        headers = {
            "user-agent": self.ua.random,
            "Connection": "keep-alive",
            # "Host": "api.batmkey.cn:8000",
            # "Upgrade-Insecure-Requests": "1",
        }

        try:
            response = requests.get(self.url,
                                    headers=headers,
                                    params=params,
                                    timeout=(100, 100),
                                    verify=False,
                                    proxies=random.choice(proxy))#,proxies=random.choice(proxy))  # , proxies=proxies

            if response.status_code == 200:
                if response.text:
                    data = response.json()
                    if isinstance(data, dict) and isinstance(data.get("aweme_list"), list):
                        print(f"还剩:{len(self.main_page_dict) - self.main_page_dict[sec_uid]} {sec_uid} success")
                        # res = data.get("data",{}).get('aweme_list')
                        res = data.get('aweme_list')
                        if res:
                            self.data_process(res)
                        else:
                            # print('self.dq.appendleft',sec_uid)
                            self.counter_sec_uid(sec_uid)  # 加到队列
                            self.dq.appendleft(sec_uid)  # count + 1
                    else:
                        if data.get('code') == 100 and data['msg'] == '没有访问权限':
                            print("报错:",data)
                        else:
                            self.counter_sec_uid(sec_uid)  # 加到队列
                            self.dq.appendleft(sec_uid)  # count + 1
                else:
                    self.dq.appendleft(sec_uid)  # 加到队列
                    self.counter_sec_uid(sec_uid)  # count + 1
                    # print("服务器没有返回数据response=",response)
                    # time.sleep(2)
                    print(sec_uid,'没有获取到数据')

            else:
                self.dq.appendleft(sec_uid) # 加到队列
                self.counter_sec_uid(sec_uid) # count + 1
                # print("状态码:",response.status_code)
                # time.sleep(0.5)
        except Exception as e:
            # print('Exception>>>>self.dq.appendleft', sec_uid)
            self.dq.appendleft(sec_uid)
            self.counter_sec_uid(sec_uid)
            # traceback.print_exc()
            print(f"还剩:{len(self.main_page_dict) - self.main_page_dict[sec_uid]} {sec_uid} fail")
            if 'timed out' not in str(e):
                traceback.print_exc()
                print(sec_uid, '报错:',e,'\n')

        time.sleep(random.choice([1, 0.8]))

    def get_header(self, vids):
        headers = {
            'authority': 'www.douyin.com',
            'accept': 'application/json',
            'accept-language': 'zh-CN,zh;q=0.9',
            'cache-control': 'max-age=0',
            'sec-ch-ua': '".Not/A)Brand";v="99", "Google Chrome";v="103", "Chromium";v="103"',
            'path': f'web/api/v2/aweme/iteminfo/?item_ids={vids}',
            'sec-ch-ua-mobile': '?0',
            'sec-ch-ua-platform': '"Windows"',
            'sec-fetch-dest': 'document',
            'sec-fetch-mode': 'navigate',
            'sec-fetch-site': 'none',
            'sec-fetch-user': '?1',
            'upgrade-insecure-requests': '1',
            'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36',
        }
        return headers

    def convert_time(self, t, vid):
        get_post_time_url = "https://www.douyin.com/web/api/v2/aweme/iteminfo/?item_ids={}"
        post_time = self.vid_dict.get(vid)
        if post_time:
            return post_time
        else:
            if t and t.rsplit('_')[-1].isdigit():
                t = int(t.rsplit('_')[-1])
                return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(t))
            else:
                res = requests.get(get_post_time_url.format(vid),
                                   headers=self.get_header(vid),
                                   verify=False)  # proxies=random.choice(proxy)
                if not res.text:
                    raise ValueError
                item = res.json()
                item = item['item_list'][0]
                # print('item_list:', len(res['item_list']))
                create_time = item["create_time"]
                post_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(int(create_time)))
                print(f"post_time:{post_time} vid:{vid}")
                return post_time
                

    def data_process(self, aweme_list):
        # print(data.keys()) #['aweme_list', 'has_more', 'log_pb', 'max_cursor', 'request_item_cursor', 'status_code']
        save_list = []
        for item in aweme_list:
            uid = item.get('author', {}).get('uid')
            if self.userid_dict.get(str(uid)):
                vid = item.get('statistics', {}).get('aweme_id', 0)
                save_data = {
                    "userid": uid,
                    "cover_pic": item.get("video", {}).get("cover", {}).get("url_list", [''])[0],
                    "content": escape_string(item.get('desc', '')),
                    "video_id": vid,
                    "comment_num": item.get('statistics', {}).get('comment_count', 0),
                    "like_num": item.get('statistics', {}).get('digg_count', 0),
                    "share_num": item.get('statistics', {}).get('share_count', 0),
                    "play_num": item.get('statistics', {}).get('play_count', 0),
                    "collect_num": item.get('statistics', {}).get('collect_count', 0),
                    "post_time": self.convert_time(item.get("video", {}).get("dynamic_cover", {}).get('uri'), vid),
                    # "post_time": self.convert_time(item.get('create_time')),
                    "url": "https://www.douyin.com/video/" + str(item.get('statistics', {}).get('aweme_id', 0)),
                }

                userid = save_data['userid']
                open_id = self.uid_oid_map.get(str(userid))
                if open_id:
                    open_id = f"'{open_id}'"
                else:
                    open_id = 'null'
                save_data['open_id'] = open_id
                save_list.append(save_data)

                # save_data.pop('url')
                # print('save_data:',save_data['post_time'],'video_id:',save_data['video_id'])
                # save_list.append(save_data)
            else:
                print("用户uid:", uid, '不存在--------------')

        # 存main表 迁移到main_true.py
        for i in save_list:
            self.db.query(self.video_sql, **i)

def loop():
    start_time = time.time()
    print("开始时间:", time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(start_time)))

    res = CrawlAima()
    # 获取所有page
    res.get_main_page()
    with ThreadPoolExecutor(max_workers=5) as t:
        obj_list = []
        for i in res.main_page_list:
            obj = t.submit(res.crawl_handler, i)
            obj_list.append(obj)

        for future in as_completed(obj_list):
            data = future.result()
    # 添加到队列
    # for i in res.main_page_list:
    #     res.dq.appendleft(i)

    crawl_fail_list = []
    while len(res.dq):
        page = res.dq.pop()
        print(f"剩余总数:{len(res.dq)} 当前page:{page}, 第 {res.counter.get(page, 0)} 抓取")
        # if res.counter.get(page, 0) > 3:  # 请求次数超过10 睡3秒
        #     time.sleep(3)

        if res.counter.get(page, 0) > 1:
            print(page, "请求次数超过3次 放弃抓取", res.counter.get(page, 0))
            crawl_fail_list.append(page)
            continue
        res.crawl_handler(page)

    print('------------3次 抓取失败----------------')
    print('抓取失败:',json.dumps(crawl_fail_list))
    print('----------------------------')
    end_time = time.time()
    print('finish', int(end_time - start_time) / 60, ' min',
          time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))


if __name__ == '__main__':
    # while 1:
    loop()
    # time.sleep(60*10)
    #

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,088评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,715评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,361评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,099评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 60,987评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,063评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,486评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,175评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,440评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,518评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,305评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,190评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,550评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,880评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,152评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,451评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,637评论 2 335

推荐阅读更多精彩内容