id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
160,363
import numpy as np import re import json import requests from gopup.economic import cons The provided code snippet includes necessary dependencies for implementing the `get_money_supply` function. Write a Python function `def get_money_supply()` to solve the following problem: 获取货币供应量数据 -------- DataFrame "月份", "货币和准货币(M2) 数量(亿元)", "货币和准货币(M2) 同比增长", "货币和准货币(M2) 环比增长", "货币(M1) 数量(亿元)", "货币(M1) 同比增长 ", "货币(M1) 环比增长", "流通中的现金(M0) 数量(亿元)", "流通中的现金(M0) 同比增长", "流通中的现金(M0) 环比增长" Here is the function: def get_money_supply(): """ 获取货币供应量数据 -------- DataFrame "月份", "货币和准货币(M2) 数量(亿元)", "货币和准货币(M2) 同比增长", "货币和准货币(M2) 环比增长", "货币(M1) 数量(亿元)", "货币(M1) 同比增长 ", "货币(M1) 环比增长", "流通中的现金(M0) 数量(亿元)", "流通中的现金(M0) 同比增长", "流通中的现金(M0) 环比增长" """ url = "http://datainterface.eastmoney.com/EM_DataCenter/JS.aspx" params = { "type": "GJZB", "sty": "ZGZB", "p": "1", "ps": "200", "mkt": "11" } r = requests.get(url=url, params=params) data_text = r.text tmp_list = data_text[data_text.find("[") + 2: -3] tmp_list = tmp_list.split('","') res_list = [] for li in tmp_list: res_list.append(li.split(',')) columns = ["月份", "货币和准货币(M2) 数量(亿元)", "货币和准货币(M2) 同比增长", "货币和准货币(M2) 环比增长", "货币(M1) 数量(亿元)", "货币(M1) 同比增长 ", "货币(M1) 环比增长", "流通中的现金(M0) 数量(亿元)", "流通中的现金(M0) 同比增长", "流通中的现金(M0) 环比增长"] data_df = pd.DataFrame(res_list, columns=columns) return data_df
获取货币供应量数据 -------- DataFrame "月份", "货币和准货币(M2) 数量(亿元)", "货币和准货币(M2) 同比增长", "货币和准货币(M2) 环比增长", "货币(M1) 数量(亿元)", "货币(M1) 同比增长 ", "货币(M1) 环比增长", "流通中的现金(M0) 数量(亿元)", "流通中的现金(M0) 同比增长", "流通中的现金(M0) 环比增长"
160,364
import numpy as np import re import json import requests from gopup.economic import cons The provided code snippet includes necessary dependencies for implementing the `get_gold_and_foreign_reserves` function. Write a Python function `def get_gold_and_foreign_reserves()` to solve the following problem: 获取外汇储备 Returns ------- DataFrame "月份", "国家外汇储备(亿美元) 数值", "国家外汇储备(亿美元) 同比", "国家外汇储备(亿美元) 环比", "黄金储备(万盎司) 数值", "黄金储备(万盎司) 同比", "黄金储备(万盎司) 环比" Here is the function: def get_gold_and_foreign_reserves(): """ 获取外汇储备 Returns ------- DataFrame "月份", "国家外汇储备(亿美元) 数值", "国家外汇储备(亿美元) 同比", "国家外汇储备(亿美元) 环比", "黄金储备(万盎司) 数值", "黄金储备(万盎司) 同比", "黄金储备(万盎司) 环比" """ url = "http://datainterface.eastmoney.com/EM_DataCenter/JS.aspx" params = { "type": "GJZB", "sty": "ZGZB", "p": "1", "ps": "200", "mkt": "16" } r = requests.get(url=url, params=params) data_text = r.text tmp_list = data_text[data_text.find("[") + 2: -3] tmp_list = tmp_list.split('","') res_list = [] for li in tmp_list: res_list.append(li.split(',')) columns = ["月份", "国家外汇储备(亿美元) 数值", "国家外汇储备(亿美元) 同比", "国家外汇储备(亿美元) 环比", "黄金储备(万盎司) 数值", "黄金储备(万盎司) 同比", "黄金储备(万盎司) 环比"] data_df = pd.DataFrame(res_list, columns=columns) return data_df
获取外汇储备 Returns ------- DataFrame "月份", "国家外汇储备(亿美元) 数值", "国家外汇储备(亿美元) 同比", "国家外汇储备(亿美元) 环比", "黄金储备(万盎司) 数值", "黄金储备(万盎司) 同比", "黄金储备(万盎司) 环比"
160,365
import numpy as np import re import json import requests from gopup.economic import cons The provided code snippet includes necessary dependencies for implementing the `get_industrial_growth` function. Write a Python function `def get_industrial_growth()` to solve the following problem: 获取工业增加值增长 Returns ------- DataFrame "月份", "同比增长%", "累计增长%" Here is the function: def get_industrial_growth(): """ 获取工业增加值增长 Returns ------- DataFrame "月份", "同比增长%", "累计增长%" """ url = "http://datainterface.eastmoney.com/EM_DataCenter/JS.aspx" params = { "type": "GJZB", "sty": "ZGZB", "p": "1", "ps": "200", "mkt": "0" } r = requests.get(url=url, params=params) data_text = r.text tmp_list = data_text[data_text.find("[") + 2: -3] tmp_list = tmp_list.split('","') res_list = [] for li in tmp_list: res_list.append(li.split(',')) columns = ["月份", "同比增长%", "累计增长%"] data_df = pd.DataFrame(res_list, columns=columns) return data_df
获取工业增加值增长 Returns ------- DataFrame "月份", "同比增长%", "累计增长%"
160,366
import numpy as np import re import json import requests from gopup.economic import cons The provided code snippet includes necessary dependencies for implementing the `get_fiscal_revenue` function. Write a Python function `def get_fiscal_revenue()` to solve the following problem: 获取财政收入 Returns ------- DataFrame "月份、当月(亿元)、同比增长、环比增长、累计(亿元)、同比增长" Here is the function: def get_fiscal_revenue(): """ 获取财政收入 Returns ------- DataFrame "月份、当月(亿元)、同比增长、环比增长、累计(亿元)、同比增长" """ url = "http://datainterface.eastmoney.com/EM_DataCenter/JS.aspx" params = { "type": "GJZB", "sty": "ZGZB", "p": "1", "ps": "200", "mkt": "14" } r = requests.get(url=url, params=params) data_text = r.text tmp_list = data_text[data_text.find("[") + 2: -3] tmp_list = tmp_list.split('","') res_list = [] for li in tmp_list: res_list.append(li.split(',')) columns = ["月份", "当月(亿元)", "同比增长", "环比增长", "累计(亿元)", "同比增长"] data_df = pd.DataFrame(res_list, columns=columns) return data_df
获取财政收入 Returns ------- DataFrame "月份、当月(亿元)、同比增长、环比增长、累计(亿元)、同比增长"
160,367
import numpy as np import re import json import requests from gopup.economic import cons The provided code snippet includes necessary dependencies for implementing the `get_consumer_total` function. Write a Python function `def get_consumer_total()` to solve the following problem: 获取社会消费品零售总额 Returns ------- DataFrame "月份、当月(亿元)、同比增长、环比增长、累计(亿元)、同比增长" Here is the function: def get_consumer_total(): """ 获取社会消费品零售总额 Returns ------- DataFrame "月份、当月(亿元)、同比增长、环比增长、累计(亿元)、同比增长" """ url = "http://datainterface.eastmoney.com/EM_DataCenter/JS.aspx" params = { "type": "GJZB", "sty": "ZGZB", "p": "1", "ps": "200", "mkt": "5" } r = requests.get(url=url, params=params) data_text = r.text tmp_list = data_text[data_text.find("[") + 2: -3] tmp_list = tmp_list.split('","') res_list = [] for li in tmp_list: res_list.append(li.split(',')) columns = ["月份", "当月(亿元)", "同比增长", "环比增长", "累计(亿元)", "同比增长"] data_df = pd.DataFrame(res_list, columns=columns) return data_df
获取社会消费品零售总额 Returns ------- DataFrame "月份、当月(亿元)、同比增长、环比增长、累计(亿元)、同比增长"
160,368
import numpy as np import re import json import requests from gopup.economic import cons The provided code snippet includes necessary dependencies for implementing the `get_credit_data` function. Write a Python function `def get_credit_data()` to solve the following problem: 获取信贷数据 Returns ------- DataFrame "月份、当月(亿元)、同比增长、环比增长、累计(亿元)、同比增长" Here is the function: def get_credit_data(): """ 获取信贷数据 Returns ------- DataFrame "月份、当月(亿元)、同比增长、环比增长、累计(亿元)、同比增长" """ url = "http://datainterface.eastmoney.com/EM_DataCenter/JS.aspx" params = { "type": "GJZB", "sty": "ZGZB", "p": "1", "ps": "200", "mkt": "7" } r = requests.get(url=url, params=params) data_text = r.text tmp_list = data_text[data_text.find("[") + 2: -3] tmp_list = tmp_list.split('","') res_list = [] for li in tmp_list: res_list.append(li.split(',')) columns = ["月份", "当月(亿元)", "同比增长", "环比增长", "累计(亿元)", "同比增长"] data_df = pd.DataFrame(res_list, columns=columns) return data_df
获取信贷数据 Returns ------- DataFrame "月份、当月(亿元)、同比增长、环比增长、累计(亿元)、同比增长"
160,369
import numpy as np import re import json import requests from gopup.economic import cons The provided code snippet includes necessary dependencies for implementing the `get_fdi_data` function. Write a Python function `def get_fdi_data()` to solve the following problem: 获取外商直接投资数据(FDI) Returns ------- DataFrame "月份、当月(亿元)、同比增长、环比增长、累计(亿元)、同比增长" Here is the function: def get_fdi_data(): """ 获取外商直接投资数据(FDI) Returns ------- DataFrame "月份、当月(亿元)、同比增长、环比增长、累计(亿元)、同比增长" """ url = "http://datainterface.eastmoney.com/EM_DataCenter/JS.aspx" params = { "type": "GJZB", "sty": "ZGZB", "p": "1", "ps": "200", "mkt": "15" } r = requests.get(url=url, params=params) data_text = r.text tmp_list = data_text[data_text.find("[") + 2: -3] tmp_list = tmp_list.split('","') res_list = [] for li in tmp_list: res_list.append(li.split(',')) columns = ["月份", "当月(十万元)", "同比增长", "环比增长", "累计(十万元)", "同比增长"] data_df = pd.DataFrame(res_list, columns=columns) # data_df['当月(亿元)'] = data_df['当月(亿元)'].map(lambda x: int(x)/100000) # data_df['累计(亿元)'] = data_df['累计(亿元)'].map(lambda x: int(x)/100000) return data_df
获取外商直接投资数据(FDI) Returns ------- DataFrame "月份、当月(亿元)、同比增长、环比增长、累计(亿元)、同比增长"
160,370
def random(n=13): from random import randint start = 10**(n-1) end = (10**n)-1 return str(randint(start, end))
null
160,371
import numpy as np import requests from gopup.economic import cons from gopup.utils import date_utils as du = {'http': 'http://', 'ftp': 'ftp://'} The provided code snippet includes necessary dependencies for implementing the `shibor_data` function. Write a Python function `def shibor_data(year=None)` to solve the following problem: 获取上海银行间同业拆放利率(Shibor) Parameters ------ year:年份(int) Return ------ date:日期 ON:隔夜拆放利率 1W:1周拆放利率 2W:2周拆放利率 1M:1个月拆放利率 3M:3个月拆放利率 6M:6个月拆放利率 9M:9个月拆放利率 1Y:1年拆放利率 http://www.shibor.org/shibor/web/html/downLoad.html?nameNew=Historical_Shibor_Data_2019.xls&downLoadPath=data&nameOld=Shibor数据2019.xls&shiborSrc=http://www.shibor.org/shibor/ Here is the function: def shibor_data(year=None): """ 获取上海银行间同业拆放利率(Shibor) Parameters ------ year:年份(int) Return ------ date:日期 ON:隔夜拆放利率 1W:1周拆放利率 2W:2周拆放利率 1M:1个月拆放利率 3M:3个月拆放利率 6M:6个月拆放利率 9M:9个月拆放利率 1Y:1年拆放利率 http://www.shibor.org/shibor/web/html/downLoad.html?nameNew=Historical_Shibor_Data_2019.xls&downLoadPath=data&nameOld=Shibor数据2019.xls&shiborSrc=http://www.shibor.org/shibor/ """ year = du.get_year() if year is None else year lab = cons.SHIBOR_TYPE['Shibor'] try: url = cons.SHIBOR_DATA_URL % (cons.P_TYPE['http'], cons.DOMAINS['shibor'], cons.PAGES['dw'], 'Shibor', year, lab, year) # url = "https://www.shibor.org/dqs/rest/cm-u-bk-shibor/ShiborHisExcel?lang=cn" herder = { "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", "Accept-Language": "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3", "Accept-Encoding": "gzip, deflate", "Connection": "keep-alive" } r = requests.get(url, headers=herder) df = pd.read_excel(r.content) df.columns = cons.SHIBOR_COLS df['date'] = df['date'].map(lambda x: x.date()) return df except Exception as e: return None
获取上海银行间同业拆放利率(Shibor) Parameters ------ year:年份(int) Return ------ date:日期 ON:隔夜拆放利率 1W:1周拆放利率 2W:2周拆放利率 1M:1个月拆放利率 3M:3个月拆放利率 6M:6个月拆放利率 9M:9个月拆放利率 1Y:1年拆放利率 http://www.shibor.org/shibor/web/html/downLoad.html?nameNew=Historical_Shibor_Data_2019.xls&downLoadPath=data&nameOld=Shibor数据2019.xls&shiborSrc=http://www.shibor.org/shibor/
160,372
import numpy as np import requests from gopup.economic import cons from gopup.utils import date_utils as du = {'http': 'http://', 'ftp': 'ftp://'} The provided code snippet includes necessary dependencies for implementing the `shibor_quote_data` function. Write a Python function `def shibor_quote_data(year=None)` to solve the following problem: 获取Shibor银行报价数据 Parameters ------ year:年份(int) Return ------ date:日期 bank:报价银行名称 ON:隔夜拆放利率 ON_B:隔夜拆放买入价 ON_A:隔夜拆放卖出价 1W_B:1周买入 1W_A:1周卖出 2W_B:买入 2W_A:卖出 1M_B:买入 1M_A:卖出 3M_B:买入 3M_A:卖出 6M_B:买入 6M_A:卖出 9M_B:买入 9M_A:卖出 1Y_B:买入 1Y_A:卖出 Here is the function: def shibor_quote_data(year=None): """ 获取Shibor银行报价数据 Parameters ------ year:年份(int) Return ------ date:日期 bank:报价银行名称 ON:隔夜拆放利率 ON_B:隔夜拆放买入价 ON_A:隔夜拆放卖出价 1W_B:1周买入 1W_A:1周卖出 2W_B:买入 2W_A:卖出 1M_B:买入 1M_A:卖出 3M_B:买入 3M_A:卖出 6M_B:买入 6M_A:卖出 9M_B:买入 9M_A:卖出 1Y_B:买入 1Y_A:卖出 """ year = du.get_year() if year is None else year lab = cons.SHIBOR_TYPE['Quote'] try: url = cons.SHIBOR_DATA_URL % (cons.P_TYPE['http'], cons.DOMAINS['shibor'], cons.PAGES['dw'], 'Quote', year, lab, year) herder = { "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", "Accept-Language": "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3", "Accept-Encoding": "gzip, deflate", "Connection": "keep-alive" } r = requests.get(url, headers=herder) df = pd.read_excel(r.content) df.columns = cons.SHIBOR_Q_COLS df['date'] = df['date'].map(lambda x: x.date()) return df except: return None
获取Shibor银行报价数据 Parameters ------ year:年份(int) Return ------ date:日期 bank:报价银行名称 ON:隔夜拆放利率 ON_B:隔夜拆放买入价 ON_A:隔夜拆放卖出价 1W_B:1周买入 1W_A:1周卖出 2W_B:买入 2W_A:卖出 1M_B:买入 1M_A:卖出 3M_B:买入 3M_A:卖出 6M_B:买入 6M_A:卖出 9M_B:买入 9M_A:卖出 1Y_B:买入 1Y_A:卖出
160,373
import numpy as np import requests from gopup.economic import cons from gopup.utils import date_utils as du = {'http': 'http://', 'ftp': 'ftp://'} The provided code snippet includes necessary dependencies for implementing the `shibor_ma_data` function. Write a Python function `def shibor_ma_data(year=None)` to solve the following problem: 获取Shibor均值数据 Parameters ------ year:年份(int) Return ------ date:日期 其它分别为各周期5、10、20均价 Here is the function: def shibor_ma_data(year=None): """ 获取Shibor均值数据 Parameters ------ year:年份(int) Return ------ date:日期 其它分别为各周期5、10、20均价 """ year = du.get_year() if year is None else year lab = cons.SHIBOR_TYPE['Tendency'] try: url = cons.SHIBOR_DATA_URL % (cons.P_TYPE['http'], cons.DOMAINS['shibor'], cons.PAGES['dw'], 'Shibor_Tendency', year, lab, year) herder = { "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", "Accept-Language": "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3", "Accept-Encoding": "gzip, deflate", "Connection": "keep-alive" } r = requests.get(url, headers=herder) df = pd.read_excel(r.content) df.columns = cons.SHIBOR_MA_COLS df['date'] = df['date'].map(lambda x: x.date()) return df except: return None
获取Shibor均值数据 Parameters ------ year:年份(int) Return ------ date:日期 其它分别为各周期5、10、20均价
160,374
import numpy as np import requests from gopup.economic import cons from gopup.utils import date_utils as du = {'http': 'http://', 'ftp': 'ftp://'} The provided code snippet includes necessary dependencies for implementing the `lpr_data` function. Write a Python function `def lpr_data(startDate, endDate)` to solve the following problem: 获取贷款市场报价利率(LPR) Parameters ------ startDate:起止日期(str) endDate:截止日期(str) Return ------ showDateCN:日期 1Y:1年贷款基础利率 5Y:5年贷款基础利率 Here is the function: def lpr_data(startDate, endDate): """ 获取贷款市场报价利率(LPR) Parameters ------ startDate:起止日期(str) endDate:截止日期(str) Return ------ showDateCN:日期 1Y:1年贷款基础利率 5Y:5年贷款基础利率 """ try: url = cons.LPR_DATA_URL herder = { "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", "Accept-Language": "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3", "Accept-Encoding": "gzip, deflate", "Connection": "keep-alive" } data = { "lang": "CN", "strStartDate": startDate, "strEndDate": endDate } r = requests.post(url, data=data, headers=herder) data_dict = json.loads(r.text)['records'] df = pd.DataFrame(data_dict) return df except: return None
获取贷款市场报价利率(LPR) Parameters ------ startDate:起止日期(str) endDate:截止日期(str) Return ------ showDateCN:日期 1Y:1年贷款基础利率 5Y:5年贷款基础利率
160,375
json import pandas as pd import requests from gopup.index.cons import index_toutiao_headers index_toutiao_headers = { "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1", 'Content-Type': 'application/json', } The provided code snippet includes necessary dependencies for implementing the `sogou_index` function. Write a Python function `def sogou_index(keyword, start_date, end_date, data_type="SEARCH_ALL")` to solve the following problem: 搜狗指数趋势数据 :param keyword: 关键词 :param start_date: 开始日期 :param end_date: 截止日期 :param data_type: 指数趋势 :return: datetime 日期 index 指数 Here is the function: def sogou_index(keyword, start_date, end_date, data_type="SEARCH_ALL"): """ 搜狗指数趋势数据 :param keyword: 关键词 :param start_date: 开始日期 :param end_date: 截止日期 :param data_type: 指数趋势 :return: datetime 日期 index 指数 """ # SEARCH_ALL 整体趋势 SEARCH_PC PC趋势 SEARCH_WAP 移动趋势 try: url = "http://zhishu.sogou.com/getDateData?kwdNamesStr=%s&startDate=%s&endDate=%s&dataType=%s&queryType=INPUT" % (keyword, start_date, end_date, data_type) res = requests.get(url, headers=index_toutiao_headers) pv_list = json.loads(res.text)['data']['pvList'][0] df = pd.DataFrame(pv_list) df['index'] = df['pv'] df = df.drop(['kwdId', 'isPeak', 'id', 'pv'], axis=1) return df except: return None
搜狗指数趋势数据 :param keyword: 关键词 :param start_date: 开始日期 :param end_date: 截止日期 :param data_type: 指数趋势 :return: datetime 日期 index 指数
160,376
import datetime import pandas as pd import requests import matplotlib.pyplot as plt from gopup.index.cons import index_weibo_headers ["font.sans-serif"] = ["SimHei"] items(word="股票"): def _get_index_data(wid, time_type): df = pd.DataFrame(data) return df def _process_index(index): if "月" in index: tmp = index.replace("日", "").split("月") date = "%04d%02d%02d" % (curr_year, int(tmp[0]), int(tmp[1])) if date > curr_date: date = "%04d%02d%02d" % (curr_year - 1, int(tmp[0]), int(tmp[1])) return date return inde try: dict_keyword = _get_items(word) df_list = [] for keyword, wid in dict_keyword.items(): df = _get_index_data(wid, time_type) if df is not None: df.columns = ["index", keyword] df["index"] = df["index"].apply(lambda x: _process_index(x)) df.set_index("index", inplace=True) df_list.append(df) if len(df_list) > 0: df = pd.concat(df_list, axis=1) if time_type == "1hour" or "1day": df.index = pd.to_datetime(df.index) else: df.index = pd.to_datetime(df.index, format="%Y%m%d") return df except: return None The provided code snippet includes necessary dependencies for implementing the `weibo_index` function. Write a Python function `def weibo_index(word="python", time_type="3month")` to solve the following problem: :param word: str :param time_type: str 1hour, 1day, 1month, 3month :return: Here is the function: def weibo_index(word="python", time_type="3month"): """ :param word: str :param time_type: str 1hour, 1day, 1month, 3month :return: """ try: dict_keyword = _get_items(word) df_list = [] for keyword, wid in dict_keyword.items(): df = _get_index_data(wid, time_type) if df is not None: df.columns = ["index", keyword] df["index"] = df["index"].apply(lambda x: _process_index(x)) df.set_index("index", inplace=True) df_list.append(df) if len(df_list) > 0: df = pd.concat(df_list, axis=1) if time_type == "1hour" or "1day": df.index = pd.to_datetime(df.index) else: df.index = pd.to_datetime(df.index, format="%Y%m%d") return df except: return None
:param word: str :param time_type: str 1hour, 1day, 1month, 3month :return:
160,377
json import pandas as pd import requests from gopup.index.cons import index_toutiao_headers index_toutiao_headers = { "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1", 'Content-Type': 'application/json', } The provided code snippet includes necessary dependencies for implementing the `toutiao_index` function. Write a Python function `def toutiao_index(keyword="python", start_date="20201016", end_date="20201022", app_name="toutiao")` to solve the following problem: 头条指数数据 :param keyword: 关键词 :param start_date: 开始日期 :param end_date: 截止日期 :param app_name: 平台 :return: datetime 日期 index 指数 Here is the function: def toutiao_index(keyword="python", start_date="20201016", end_date="20201022", app_name="toutiao"): """ 头条指数数据 :param keyword: 关键词 :param start_date: 开始日期 :param end_date: 截止日期 :param app_name: 平台 :return: datetime 日期 index 指数 """ # list_keyword = '["%s"]' % keyword try: url = "https://trendinsight.oceanengine.com/api/open/index/get_multi_keyword_hot_trend" data = { "keyword_list": [keyword], "start_date": start_date, "end_date": end_date, "app_name": app_name } res = requests.post(url, json=data, headers=index_toutiao_headers) hot_list = json.loads(res.text)['data']['hot_list'][0]['hot_list'] df = pd.DataFrame(hot_list) return df except: return None
头条指数数据 :param keyword: 关键词 :param start_date: 开始日期 :param end_date: 截止日期 :param app_name: 平台 :return: datetime 日期 index 指数
160,378
json import pandas as pd import requests from gopup.index.cons import index_toutiao_headers index_toutiao_headers = { "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1", 'Content-Type': 'application/json', } The provided code snippet includes necessary dependencies for implementing the `toutiao_relation` function. Write a Python function `def toutiao_relation(keyword="python", start_date="20201012", end_date="20201018", app_name="toutiao")` to solve the following problem: 头条相关分析 :param keyword: 关键词 :param start_date: 开始日期 :param end_date: 截止日期 :return: relation_word 相关词 relation_score 相关性值 score_rank 相关性值排名 search_hot 搜索热点值 search_ratio 搜索比率 Here is the function: def toutiao_relation(keyword="python", start_date="20201012", end_date="20201018", app_name="toutiao"): """ 头条相关分析 :param keyword: 关键词 :param start_date: 开始日期 :param end_date: 截止日期 :return: relation_word 相关词 relation_score 相关性值 score_rank 相关性值排名 search_hot 搜索热点值 search_ratio 搜索比率 """ try: url = "https://trendinsight.oceanengine.com/api/open/index/get_relation_word" data = {"param": {"keyword": keyword, "start_date": start_date, "end_date": end_date, "app_name": app_name} } res = requests.post(url, json=data, headers=index_toutiao_headers) relation_word_list = json.loads(res.text)['data']['relation_word_list'] df = pd.DataFrame(relation_word_list) return df except: return None
头条相关分析 :param keyword: 关键词 :param start_date: 开始日期 :param end_date: 截止日期 :return: relation_word 相关词 relation_score 相关性值 score_rank 相关性值排名 search_hot 搜索热点值 search_ratio 搜索比率
160,379
json import pandas as pd import requests from gopup.index.cons import index_toutiao_headers index_toutiao_headers = { "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1", 'Content-Type': 'application/json', } The provided code snippet includes necessary dependencies for implementing the `toutiao_province` function. Write a Python function `def toutiao_province(keyword="python", start_date="20201012", end_date="20201018", app_name="toutiao")` to solve the following problem: 头条地域分析 :param keyword: 关键词 :param start_date: 开始日期 :param end_date: 截止日期 :return: name 省份 value 渗透率 Here is the function: def toutiao_province(keyword="python", start_date="20201012", end_date="20201018", app_name="toutiao"): """ 头条地域分析 :param keyword: 关键词 :param start_date: 开始日期 :param end_date: 截止日期 :return: name 省份 value 渗透率 """ try: url = "https://trendinsight.oceanengine.com/api/open/index/get_portrait" data = {"param": {"keyword": keyword, "start_date": start_date, "end_date": end_date, "app_name": app_name} } res = requests.post(url, json=data, headers=index_toutiao_headers) res_text = json.loads(res.text)['data']['data'][2]['label_list'] df = pd.DataFrame(res_text) df['name'] = df['name_zh'] df = df.drop(['label_id', 'name_zh'], axis=1) df = df.sort_values(by="value", ascending=False) return df except: return None
头条地域分析 :param keyword: 关键词 :param start_date: 开始日期 :param end_date: 截止日期 :return: name 省份 value 渗透率
160,380
json import pandas as pd import requests from gopup.index.cons import index_toutiao_headers index_toutiao_headers = { "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1", 'Content-Type': 'application/json', } The provided code snippet includes necessary dependencies for implementing the `toutiao_city` function. Write a Python function `def toutiao_city(keyword="python", start_date="20201012", end_date="20201018", app_name="toutiao")` to solve the following problem: 头条城市分析 :param keyword: 关键词 :param start_date: 开始日期 :param end_date: 截止日期 :return: name 城市 value 渗透率 Here is the function: def toutiao_city(keyword="python", start_date="20201012", end_date="20201018", app_name="toutiao"): """ 头条城市分析 :param keyword: 关键词 :param start_date: 开始日期 :param end_date: 截止日期 :return: name 城市 value 渗透率 """ try: url = "https://trendinsight.oceanengine.com/api/open/index/get_portrait" data = {"param": {"keyword": keyword, "start_date": start_date, "end_date": end_date, "app_name": app_name} } res = requests.post(url, json=data, headers=index_toutiao_headers) res_text = json.loads(res.text)['data']['data'][3]['label_list'] df = pd.DataFrame(res_text) df['name'] = df['name_zh'] df = df.drop(['label_id', 'name_zh'], axis=1) df = df.sort_values(by="value", ascending=False) return df except: return None
头条城市分析 :param keyword: 关键词 :param start_date: 开始日期 :param end_date: 截止日期 :return: name 城市 value 渗透率
160,381
json import pandas as pd import requests from gopup.index.cons import index_toutiao_headers index_toutiao_headers = { "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1", 'Content-Type': 'application/json', } The provided code snippet includes necessary dependencies for implementing the `toutiao_age` function. Write a Python function `def toutiao_age(keyword="python", start_date="20201012", end_date="20201018", app_name="toutiao")` to solve the following problem: 头条年龄分析 :param keyword: 关键词 :param start_date: 开始日期 :param end_date: 截止日期 :return: name 年龄区间 value 渗透率 Here is the function: def toutiao_age(keyword="python", start_date="20201012", end_date="20201018", app_name="toutiao"): """ 头条年龄分析 :param keyword: 关键词 :param start_date: 开始日期 :param end_date: 截止日期 :return: name 年龄区间 value 渗透率 """ try: url = "https://trendinsight.oceanengine.com/api/open/index/get_portrait" data = {"param": {"keyword": keyword, "start_date": start_date, "end_date": end_date, "app_name": app_name} } res = requests.post(url, json=data, headers=index_toutiao_headers) res_text = json.loads(res.text)['data']['data'][0]['label_list'] df = pd.DataFrame(res_text) df['name'] = df['name_zh'] df = df.drop(['label_id', 'name_zh'], axis=1) return df except: return None
头条年龄分析 :param keyword: 关键词 :param start_date: 开始日期 :param end_date: 截止日期 :return: name 年龄区间 value 渗透率
160,382
json import pandas as pd import requests from gopup.index.cons import index_toutiao_headers index_toutiao_headers = { "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1", 'Content-Type': 'application/json', } The provided code snippet includes necessary dependencies for implementing the `toutiao_gender` function. Write a Python function `def toutiao_gender(keyword="python", start_date="202308001", end_date="202308017", app_name="toutiao")` to solve the following problem: 头条性别分析 :param keyword: 关键词 :param start_date: 开始日期 :param end_date: 截止日期 :return: name 性别 value 渗透率 Here is the function: def toutiao_gender(keyword="python", start_date="202308001", end_date="202308017", app_name="toutiao"): """ 头条性别分析 :param keyword: 关键词 :param start_date: 开始日期 :param end_date: 截止日期 :return: name 性别 value 渗透率 """ try: url = "https://trendinsight.oceanengine.com/api/open/index/get_portrait" data = {"param": {"keyword": keyword, "start_date": start_date, "end_date": end_date, "app_name": app_name} } res = requests.post(url, json=data, headers=index_toutiao_headers) res_text = json.loads(res.text)['data']['data'][1]['label_list'] df = pd.DataFrame(res_text) df['name'] = df['name_zh'] df = df.drop(['label_id', 'name_zh'], axis=1) df = df.sort_values(by="value", ascending=False) return df except: return None
头条性别分析 :param keyword: 关键词 :param start_date: 开始日期 :param end_date: 截止日期 :return: name 性别 value 渗透率
160,383
json import pandas as pd import requests from gopup.index.cons import index_toutiao_headers index_toutiao_headers = { "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1", 'Content-Type': 'application/json', } The provided code snippet includes necessary dependencies for implementing the `toutiao_interest_category` function. Write a Python function `def toutiao_interest_category(keyword="python", start_date="20201012", end_date="20201018", app_name="toutiao")` to solve the following problem: 头条用户阅读兴趣分类 :param keyword: 关键词 :param start_date: 开始日期 :param end_date: 截止日期 :return: name 分类 value 渗透率 Here is the function: def toutiao_interest_category(keyword="python", start_date="20201012", end_date="20201018", app_name="toutiao"): """ 头条用户阅读兴趣分类 :param keyword: 关键词 :param start_date: 开始日期 :param end_date: 截止日期 :return: name 分类 value 渗透率 """ try: url = "https://trendinsight.oceanengine.com/api/open/index/get_portrait" data = {"param": {"keyword": keyword, "start_date": start_date, "end_date": end_date, "app_name": app_name} } res = requests.post(url, json=data, headers=index_toutiao_headers) res_text = json.loads(res.text)['data']['data'][4]['label_list'] df = pd.DataFrame(res_text) df['name'] = df['name_zh'] df = df.drop(['label_id', 'name_zh'], axis=1) df = df.sort_values(by="value", ascending=False) return df except: return None
头条用户阅读兴趣分类 :param keyword: 关键词 :param start_date: 开始日期 :param end_date: 截止日期 :return: name 分类 value 渗透率
160,384
import json import pandas as pd import requests from urllib.parse import quote import copy from typing import Optional from urllib3 import Retry def nested_to_record( ds, prefix: str = "", sep: str = ".", level: int = 0, max_level: Optional[int] = None, ): """ """ singleton = False if isinstance(ds, dict): ds = [ds] singleton = True new_ds = [] for d in ds: new_d = copy.deepcopy(d) for k, v in d.items(): # each key gets renamed with prefix if not isinstance(k, str): k = str(k) if level == 0: newkey = k else: newkey = prefix + sep + k # flatten if type is dict and # current dict level < maximum level provided and # only dicts gets recurse-flattened # only at level>1 do we rename the rest of the keys if not isinstance(v, dict) or ( max_level is not None and level >= max_level ): if level != 0: # so we skip copying for top level, common case v = new_d.pop(k) new_d[newkey] = v continue else: v = new_d.pop(k) new_d.update(nested_to_record(v, newkey, sep, level + 1, max_level)) new_ds.append(new_d) if singleton: return new_ds[0] return new_ds
null
160,385
import decrypt_func, get_encrypt_json, format_data, get_key, format_data_feed, format_data_new import pandas as pd import requests import datetime import json import math The provided code snippet includes necessary dependencies for implementing the `decrypt` function. Write a Python function `def decrypt(t: str, e: str) -> str` to solve the following problem: 解密函数 :param t: :type t: :param e: :type e: :return: :rtype: Here is the function: def decrypt(t: str, e: str) -> str: """ 解密函数 :param t: :type t: :param e: :type e: :return: :rtype: """ n, i, a, result = list(t), list(e), {}, [] ln = int(len(n) / 2) start, end = n[ln:], n[:ln] a = dict(zip(end, start)) return "".join([a[j] for j in e])
解密函数 :param t: :type t: :param e: :type e: :return: :rtype:
160,386
import decrypt_func, get_encrypt_json, format_data, get_key, format_data_feed, format_data_new import pandas as pd import requests import datetime import json import math def get_ptbk(uniqid: str, cookie: str) -> str: headers = { "Accept": "application/json, text/plain, */*", "Accept-Encoding": "gzip, deflate", "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8", "Connection": "keep-alive", "Cookie": cookie, "Host": "index.baidu.com", "Referer": "http://index.baidu.com/v2/main/index.html", "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.90 Safari/537.36", "X-Requested-With": "XMLHttpRequest", } session = requests.Session() session.headers.update(headers) with session.get( url=f"http://index.baidu.com/Interface/ptbk?uniqid={uniqid}" ) as response: ptbk = response.json()["data"] return ptbk
null
160,387
import decrypt_func, get_encrypt_json, format_data, get_key, format_data_feed, format_data_new import pandas as pd import requests import datetime import json import math The provided code snippet includes necessary dependencies for implementing the `baidu_interest_index` function. Write a Python function `def baidu_interest_index(word, cookie)` to solve the following problem: 百度指数 人群画像兴趣分布 :param word: 关键词 :param cookie: :return: desc 兴趣分类 tgi TGI指数 word_rate 关键词分布比率 all_rate 全网分布比率 period 周期范围 Here is the function: def baidu_interest_index(word, cookie): """ 百度指数 人群画像兴趣分布 :param word: 关键词 :param cookie: :return: desc 兴趣分类 tgi TGI指数 word_rate 关键词分布比率 all_rate 全网分布比率 period 周期范围 """ try: headers = { "Accept": "application/json, text/plain, */*", "Accept-Encoding": "gzip, deflate", "Accept-Language": "zh-CN,zh;q=0.9", "Cache-Control": "no-cache", "Cookie": cookie, "DNT": "1", "Host": "index.baidu.com", "Pragma": "no-cache", "Proxy-Connection": "keep-alive", "Referer": "zhishu.baidu.com", "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.90 Safari/537.36", "X-Requested-With": "XMLHttpRequest", } url = "http://index.baidu.com/api/SocialApi/interest?wordlist[]=%s" % word r = requests.get(url=url, headers=headers) data = json.loads(r.text)['data'] period = "%s|%s" % (data['startDate'], data['endDate']) age_list = data['result'][0]['interest'] age_df = pd.DataFrame(age_list) all_list = data['result'][1]['interest'] all_df = pd.DataFrame(all_list) all_df.drop(["tgi", "typeId"], axis=1, inplace=True) res_df = pd.merge(age_df, all_df, on='desc') res_df['period'] = period res_df.drop(["typeId"], axis=1, inplace=True) res_df.rename(columns={'rate_x': 'word_rate', 'rate_y': 'all_rate'}, inplace=True) return res_df except: return None
百度指数 人群画像兴趣分布 :param word: 关键词 :param cookie: :return: desc 兴趣分类 tgi TGI指数 word_rate 关键词分布比率 all_rate 全网分布比率 period 周期范围
160,388
import decrypt_func, get_encrypt_json, format_data, get_key, format_data_feed, format_data_new import pandas as pd import requests import datetime import json import math The provided code snippet includes necessary dependencies for implementing the `baidu_gender_index` function. Write a Python function `def baidu_gender_index(word, cookie)` to solve the following problem: 百度指数 人群画像性别分布 :param word: 关键词 :param cookie: :return: desc 性别 tgi TGI指数 word_rate 关键词分布比率 all_rate 全网分布比率 period 周期范围 Here is the function: def baidu_gender_index(word, cookie): """ 百度指数 人群画像性别分布 :param word: 关键词 :param cookie: :return: desc 性别 tgi TGI指数 word_rate 关键词分布比率 all_rate 全网分布比率 period 周期范围 """ try: headers = { "Accept": "application/json, text/plain, */*", "Accept-Encoding": "gzip, deflate", "Accept-Language": "zh-CN,zh;q=0.9", "Cache-Control": "no-cache", "Cookie": cookie, "DNT": "1", "Host": "index.baidu.com", "Pragma": "no-cache", "Proxy-Connection": "keep-alive", "Referer": "zhishu.baidu.com", "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.90 Safari/537.36", "X-Requested-With": "XMLHttpRequest", } url = "http://index.baidu.com/api/SocialApi/baseAttributes?wordlist[]=%s" % word r = requests.get(url=url, headers=headers) data = json.loads(r.text)['data'] period = "%s|%s" % (data['startDate'], data['endDate']) age_list = data['result'][0]['gender'] age_df = pd.DataFrame(age_list) all_list = data['result'][1]['gender'] all_df = pd.DataFrame(all_list) all_df.drop(["tgi", "typeId"], axis=1, inplace=True) res_df = pd.merge(age_df, all_df, on='desc') res_df['period'] = period res_df.drop(["typeId"], axis=1, inplace=True) res_df.rename(columns={'rate_x': 'word_rate', 'rate_y': 'all_rate'}, inplace=True) return res_df except: return None
百度指数 人群画像性别分布 :param word: 关键词 :param cookie: :return: desc 性别 tgi TGI指数 word_rate 关键词分布比率 all_rate 全网分布比率 period 周期范围
160,389
import decrypt_func, get_encrypt_json, format_data, get_key, format_data_feed, format_data_new import pandas as pd import requests import datetime import json import math The provided code snippet includes necessary dependencies for implementing the `baidu_age_index` function. Write a Python function `def baidu_age_index(word, cookie)` to solve the following problem: 百度指数 人群画像年龄分布 :param word: 关键词 :param cookie: :return: desc 年龄范围 tgi TGI指数 word_rate 关键词分布比率 all_rate 全网分布比率 period 周期范围 Here is the function: def baidu_age_index(word, cookie): """ 百度指数 人群画像年龄分布 :param word: 关键词 :param cookie: :return: desc 年龄范围 tgi TGI指数 word_rate 关键词分布比率 all_rate 全网分布比率 period 周期范围 """ try: headers = { "Accept": "application/json, text/plain, */*", "Accept-Encoding": "gzip, deflate", "Accept-Language": "zh-CN,zh;q=0.9", "Cache-Control": "no-cache", "Cookie": cookie, "DNT": "1", "Host": "index.baidu.com", "Pragma": "no-cache", "Proxy-Connection": "keep-alive", "Referer": "zhishu.baidu.com", "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.90 Safari/537.36", "X-Requested-With": "XMLHttpRequest", } url = "http://index.baidu.com/api/SocialApi/baseAttributes?wordlist[]=%s" % word r = requests.get(url=url, headers=headers) data = json.loads(r.text)['data'] period = "%s|%s" % (data['startDate'], data['endDate']) age_list = data['result'][0]['age'] age_df = pd.DataFrame(age_list) all_list = data['result'][1]['age'] all_df = pd.DataFrame(all_list) all_df.drop(["tgi", "typeId"], axis=1, inplace=True) res_df = pd.merge(age_df, all_df, on='desc') res_df['period'] = period res_df.drop(["typeId"], axis=1, inplace=True) res_df.rename(columns={'rate_x': 'word_rate', 'rate_y': 'all_rate'}, inplace=True) return res_df except: return None
百度指数 人群画像年龄分布 :param word: 关键词 :param cookie: :return: desc 年龄范围 tgi TGI指数 word_rate 关键词分布比率 all_rate 全网分布比率 period 周期范围
160,390
import decrypt_func, get_encrypt_json, format_data, get_key, format_data_feed, format_data_new import pandas as pd import requests import datetime import json import math The provided code snippet includes necessary dependencies for implementing the `baidu_atlas_index` function. Write a Python function `def baidu_atlas_index(word, cookie, date=None)` to solve the following problem: 百度指数 需求图谱 :param word: 关键词 :param cookie: :param date: 周期 :return: period 周期范围 word 相关词 pv 搜索热度 ratio 搜索变化率 Here is the function: def baidu_atlas_index(word, cookie, date=None): """ 百度指数 需求图谱 :param word: 关键词 :param cookie: :param date: 周期 :return: period 周期范围 word 相关词 pv 搜索热度 ratio 搜索变化率 """ try: headers = { "Accept": "application/json, text/plain, */*", "Accept-Encoding": "gzip, deflate", "Accept-Language": "zh-CN,zh;q=0.9", "Cache-Control": "no-cache", "Cookie": cookie, "DNT": "1", "Host": "index.baidu.com", "Pragma": "no-cache", "Proxy-Connection": "keep-alive", "Referer": "zhishu.baidu.com", "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.90 Safari/537.36", "X-Requested-With": "XMLHttpRequest", } if date == None: date = "" url = "http://index.baidu.com/api/WordGraph/multi?wordlist[]=%s&datelist=%s" % (word, date) r = requests.get(url=url, headers=headers) data = json.loads(r.text)['data'] wordlist = data['wordlist'][0]['wordGraph'] res_list = [] for word in wordlist: tmp = { "word": word['word'], "pv": word['pv'], "ratio": word['ratio'], "period": data['period'], "sim": word['sim'] } res_list.append(tmp) df = pd.DataFrame(res_list) return df except: return None
百度指数 需求图谱 :param word: 关键词 :param cookie: :param date: 周期 :return: period 周期范围 word 相关词 pv 搜索热度 ratio 搜索变化率
160,391
.index.baidu_decrypt import decrypt_func, get_encrypt_json, format_data, get_key, format_data_feed, format_data_new import pandas as pd import requests import datetime import json import math def decrypt_func(key: str, data: str) -> List[str]: """ 数据解密方法 """ a = key i = data n = {} s = [] for o in range(len(a)//2): n[a[o]] = a[len(a)//2 + o] for r in range(len(data)): s.append(n[i[r]]) return ''.join(s).split(',') def get_encrypt_json( *, start_date: str, end_date: str, keywords: List[List[str]], type: str, area: int, cookies: str ) -> Dict: pre_url_map = { 'search': 'http://index.baidu.com/api/SearchApi/index?', 'live': 'http://index.baidu.com/api/LiveApi/getLive?', 'news': 'http://index.baidu.com/api/NewsApi/getNewsIndex?', 'feed': 'http://index.baidu.com/api/FeedSearchApi/getFeedIndex?' } pre_url = pre_url_map[type] word_list = [ [{'name': keyword, 'wordType': 1} for keyword in keyword_list] for keyword_list in keywords ] if type == 'live': request_args = { 'word': json.dumps(word_list), 'region': area } else: request_args = { 'word': json.dumps(word_list), 'startDate': start_date, 'endDate': end_date, 'area': area } url = pre_url + urlencode(request_args) cipher_text = get_cipher_text(keywords[0][0]) html = http_get(url, cookies, cipher_text=cipher_text) datas = json.loads(html) if datas['status'] == 10000: raise GopupError(ErrorCode.NO_LOGIN) if datas["status"] == 10001: raise GopupError(ErrorCode.REQUEST_LIMITED) if datas['status'] != 0: raise GopupError(ErrorCode.UNKNOWN, str(datas)) return datas def get_key(uniqid: str, cookies: str) -> str: url = 'http://index.baidu.com/Interface/api/ptbk?uniqid=%s' % uniqid html = http_get(url, cookies) datas = json.loads(html) key = datas['data'] return key def format_data(data: Dict, kind: str): """ 格式化堆在一起的数据 """ keyword = str(data['word']) start_date = datetime.datetime.strptime(data['all']['startDate'], '%Y-%m-%d') end_date = datetime.datetime.strptime(data['all']['endDate'], '%Y-%m-%d') date_list = [] while start_date <= end_date: date_list.append(start_date) start_date += datetime.timedelta(days=1) # for kind in ALL_KIND: index_datas = data[kind]['data'] for i, cur_date in enumerate(date_list): try: index_data = index_datas[i] except IndexError: index_data = '' formated_data = { 'keyword': [keyword_info['name'] for keyword_info in json.loads(keyword.replace('\'', '"'))][0], 'type': kind, 'date': cur_date.strftime('%Y-%m-%d'), 'index': index_data if index_data else '0' } yield formated_data def baidu_search_index(word, start_date, end_date, cookie, type="all"): # 百度搜索数据 try: keywords_list = [[word]] encrypt_json = get_encrypt_json( start_date=start_date, end_date=end_date, keywords=keywords_list, type='search', area=0, cookies=cookie ) encrypt_datas = encrypt_json['data']['userIndexes'] uniqid = encrypt_json['data']['uniqid'] result = [] key = get_key(uniqid, cookie) for encrypt_data in encrypt_datas: encrypt_data[type]['data'] = decrypt_func(key, encrypt_data[type]['data']) for formated_data in format_data(encrypt_data, kind=type): result.append(formated_data) # yield formated_data data_df = pd.DataFrame(result) data_df.index = pd.to_datetime(data_df["date"]) del data_df["date"] return data_df except Exception as e: return None
null
160,392
.index.baidu_decrypt import decrypt_func, get_encrypt_json, format_data, get_key, format_data_feed, format_data_new import pandas as pd import requests import datetime import json import math def decrypt_func(key: str, data: str) -> List[str]: """ 数据解密方法 """ a = key i = data n = {} s = [] for o in range(len(a)//2): n[a[o]] = a[len(a)//2 + o] for r in range(len(data)): s.append(n[i[r]]) return ''.join(s).split(',') def get_encrypt_json( *, start_date: str, end_date: str, keywords: List[List[str]], type: str, area: int, cookies: str ) -> Dict: pre_url_map = { 'search': 'http://index.baidu.com/api/SearchApi/index?', 'live': 'http://index.baidu.com/api/LiveApi/getLive?', 'news': 'http://index.baidu.com/api/NewsApi/getNewsIndex?', 'feed': 'http://index.baidu.com/api/FeedSearchApi/getFeedIndex?' } pre_url = pre_url_map[type] word_list = [ [{'name': keyword, 'wordType': 1} for keyword in keyword_list] for keyword_list in keywords ] if type == 'live': request_args = { 'word': json.dumps(word_list), 'region': area } else: request_args = { 'word': json.dumps(word_list), 'startDate': start_date, 'endDate': end_date, 'area': area } url = pre_url + urlencode(request_args) cipher_text = get_cipher_text(keywords[0][0]) html = http_get(url, cookies, cipher_text=cipher_text) datas = json.loads(html) if datas['status'] == 10000: raise GopupError(ErrorCode.NO_LOGIN) if datas["status"] == 10001: raise GopupError(ErrorCode.REQUEST_LIMITED) if datas['status'] != 0: raise GopupError(ErrorCode.UNKNOWN, str(datas)) return datas def get_key(uniqid: str, cookies: str) -> str: url = 'http://index.baidu.com/Interface/api/ptbk?uniqid=%s' % uniqid html = http_get(url, cookies) datas = json.loads(html) key = datas['data'] return key def format_data_feed(data: Dict): keyword = str(data['key']) start_date = datetime.datetime.strptime(data['startDate'], '%Y-%m-%d') end_date = datetime.datetime.strptime(data['endDate'], '%Y-%m-%d') date_list = [] while start_date <= end_date: date_list.append(start_date) start_date += datetime.timedelta(days=1) index_datas = data['data'] for i, cur_date in enumerate(date_list): try: index_data = index_datas[i] except IndexError: index_data = '' formated_data = { 'keyword': [keyword_info['name'] for keyword_info in json.loads(keyword.replace('\'', '"'))][0], 'date': cur_date.strftime('%Y-%m-%d'), 'index': index_data if index_data else '0' } yield formated_data def baidu_info_index(word, start_date, end_date, cookie): # 百度资讯指数 try: keywords_list = [[word]] encrypt_json = get_encrypt_json( start_date=start_date, end_date=end_date, keywords=keywords_list, type='feed', area=0, cookies=cookie ) encrypt_datas = encrypt_json['data']['index'] uniqid = encrypt_json['data']['uniqid'] result = [] key = get_key(uniqid, cookie) for encrypt_data in encrypt_datas: encrypt_data['data'] = decrypt_func(key, encrypt_data['data']) for formated_data in format_data_feed(encrypt_data): result.append(formated_data) # yield formated_data data_df = pd.DataFrame(result) data_df.index = pd.to_datetime(data_df["date"]) del data_df["date"] return data_df except Exception as e: return None
null
160,393
.index.baidu_decrypt import decrypt_func, get_encrypt_json, format_data, get_key, format_data_feed, format_data_new import pandas as pd import requests import datetime import json import math def decrypt_func(key: str, data: str) -> List[str]: """ 数据解密方法 """ a = key i = data n = {} s = [] for o in range(len(a)//2): n[a[o]] = a[len(a)//2 + o] for r in range(len(data)): s.append(n[i[r]]) return ''.join(s).split(',') def get_encrypt_json( *, start_date: str, end_date: str, keywords: List[List[str]], type: str, area: int, cookies: str ) -> Dict: pre_url_map = { 'search': 'http://index.baidu.com/api/SearchApi/index?', 'live': 'http://index.baidu.com/api/LiveApi/getLive?', 'news': 'http://index.baidu.com/api/NewsApi/getNewsIndex?', 'feed': 'http://index.baidu.com/api/FeedSearchApi/getFeedIndex?' } pre_url = pre_url_map[type] word_list = [ [{'name': keyword, 'wordType': 1} for keyword in keyword_list] for keyword_list in keywords ] if type == 'live': request_args = { 'word': json.dumps(word_list), 'region': area } else: request_args = { 'word': json.dumps(word_list), 'startDate': start_date, 'endDate': end_date, 'area': area } url = pre_url + urlencode(request_args) cipher_text = get_cipher_text(keywords[0][0]) html = http_get(url, cookies, cipher_text=cipher_text) datas = json.loads(html) if datas['status'] == 10000: raise GopupError(ErrorCode.NO_LOGIN) if datas["status"] == 10001: raise GopupError(ErrorCode.REQUEST_LIMITED) if datas['status'] != 0: raise GopupError(ErrorCode.UNKNOWN, str(datas)) return datas def get_key(uniqid: str, cookies: str) -> str: url = 'http://index.baidu.com/Interface/api/ptbk?uniqid=%s' % uniqid html = http_get(url, cookies) datas = json.loads(html) key = datas['data'] return key def format_data_new(data: Dict): keyword = str(data['key']) start_date = datetime.datetime.strptime(data['startDate'], '%Y-%m-%d') end_date = datetime.datetime.strptime(data['endDate'], '%Y-%m-%d') date_list = [] while start_date <= end_date: date_list.append(start_date) start_date += datetime.timedelta(days=1) index_datas = data['data'] for i, cur_date in enumerate(date_list): try: index_data = index_datas[i] except IndexError: index_data = '' formated_data = { 'keyword': [keyword_info['name'] for keyword_info in json.loads(keyword.replace('\'', '"'))][0], 'date': cur_date.strftime('%Y-%m-%d'), 'index': index_data if index_data else '0' } yield formated_data def baidu_media_index(word, start_date, end_date, cookie): # 百度媒体指数 try: keywords_list = [[word]] encrypt_json = get_encrypt_json( start_date=start_date, end_date=end_date, keywords=keywords_list, type='news', area=0, cookies=cookie ) encrypt_datas = encrypt_json['data']['index'] uniqid = encrypt_json['data']['uniqid'] result = [] key = get_key(uniqid, cookie) for encrypt_data in encrypt_datas: encrypt_data['data'] = decrypt_func(key, encrypt_data['data']) for formated_data in format_data_new(encrypt_data): result.append(formated_data) # yield formated_data data_df = pd.DataFrame(result) data_df.index = pd.to_datetime(data_df["date"]) del data_df["date"] return data_df except Exception as e: return None
null
160,394
import requests from gopup.index.cons import headers from gopup.index.google_request import TrendReq from gopup.utils.date_utils import int2time class TrendReq(object): """ Google Trends API """ GET_METHOD = "get" POST_METHOD = "post" GENERAL_URL = "https://trends.google.com/trends/api/explore" INTEREST_OVER_TIME_URL = "https://trends.google.com/trends/api/widgetdata/multiline" INTEREST_BY_REGION_URL = ( "https://trends.google.com/trends/api/widgetdata/comparedgeo" ) RELATED_QUERIES_URL = ( "https://trends.google.com/trends/api/widgetdata/relatedsearches" ) TRENDING_SEARCHES_URL = ( "https://trends.google.com/trends/hottrends/visualize/internal/data" ) TOP_CHARTS_URL = "https://trends.google.com/trends/api/topcharts" SUGGESTIONS_URL = "https://trends.google.com/trends/api/autocomplete/" CATEGORIES_URL = "https://trends.google.com/trends/api/explore/pickers/category" TODAY_SEARCHES_URL = "https://trends.google.com/trends/api/dailytrends" def __init__( self, hl="en-US", tz=360, geo="", timeout=(2, 5), proxies="", retries=0, backoff_factor=0, ): """ Initialize default values for params """ # google rate limit self.google_rl = "You have reached your quota limit. Please try again later." self.results = None # set user defined options used globally self.tz = tz self.hl = hl self.geo = geo self.kw_list = list() self.timeout = timeout self.proxies = proxies # add a proxy option self.retries = retries self.backoff_factor = backoff_factor self.proxy_index = 0 self.cookies = self.GetGoogleCookie() # intialize widget payloads self.token_payload = dict() self.interest_over_time_widget = dict() self.interest_by_region_widget = dict() self.related_topics_widget_list = list() self.related_queries_widget_list = list() def GetGoogleCookie(self): """ Gets google cookie (used for each and every proxy; once on init otherwise) Removes proxy from the list on proxy error """ while True: if len(self.proxies) > 0: proxy = {"https": self.proxies[self.proxy_index]} else: proxy = "" try: return dict( filter( lambda i: i[0] == "NID", requests.get( "https://trends.google.com/?geo={geo}".format( geo=self.hl[-2:] ), timeout=self.timeout, proxies=proxy, ).cookies.items(), ) ) except requests.exceptions.ProxyError: print("Proxy error. Changing IP") if len(self.proxies) > 0: self.proxies.remove(self.proxies[self.proxy_index]) else: print("Proxy list is empty. Bye!") continue def GetNewProxy(self): """ Increment proxy INDEX; zero on overflow """ if self.proxy_index < (len(self.proxies) - 1): self.proxy_index += 1 else: self.proxy_index = 0 def _get_data(self, url, method=GET_METHOD, trim_chars=0, **kwargs): """Send a request to Google and return the JSON response as a Python object :param url: the url to which the request will be sent :param method: the HTTP method ('get' or 'post') :param trim_chars: how many characters should be trimmed off the beginning of the content of the response before this is passed to the JSON parser :param kwargs: any extra key arguments passed to the request builder (usually query parameters or data) :return: """ s = requests.session() # Retries mechanism. Activated when one of statements >0 (best used for proxy) if self.retries > 0 or self.backoff_factor > 0: retry = Retry( total=self.retries, read=self.retries, connect=self.retries, backoff_factor=self.backoff_factor, ) s.headers.update({"accept-language": self.hl}) if len(self.proxies) > 0: self.cookies = self.GetGoogleCookie() s.proxies.update({"https": self.proxies[self.proxy_index]}) if method == TrendReq.POST_METHOD: response = s.post( url, timeout=self.timeout, cookies=self.cookies, **kwargs ) # DO NOT USE retries or backoff_factor here else: response = s.get( url, timeout=self.timeout, cookies=self.cookies, **kwargs ) # DO NOT USE retries or backoff_factor here # check if the response contains json and throw an exception otherwise # Google mostly sends 'application/json' in the Content-Type header, # but occasionally it sends 'application/javascript # and sometimes even 'text/javascript if ( response.status_code == 200 and "application/json" in response.headers["Content-Type"] or "application/javascript" in response.headers["Content-Type"] or "text/javascript" in response.headers["Content-Type"] ): # trim initial characters # some responses start with garbage characters, like ")]}'," # these have to be cleaned before being passed to the json parser content = response.text[trim_chars:] # parse json self.GetNewProxy() return json.loads(content) else: # error # raise "The request failed: Google returned a ……" print("The request failed: Google returned a ……") def build_payload(self, kw_list, cat=0, timeframe="today 5-y", geo="", gprop=""): """Create the payload for related queries, interest over time and interest by region""" self.kw_list = kw_list self.geo = geo or self.geo self.token_payload = { "hl": self.hl, "tz": self.tz, "req": {"comparisonItem": [], "category": cat, "property": gprop}, } # build out json for each keyword for kw in self.kw_list: keyword_payload = {"keyword": kw, "time": timeframe, "geo": self.geo} self.token_payload["req"]["comparisonItem"].append(keyword_payload) # requests will mangle this if it is not a string self.token_payload["req"] = json.dumps(self.token_payload["req"]) # get tokens self._tokens() return def _tokens(self): """Makes request to Google to get API tokens for interest over time, interest by region and related queries""" # make the request and parse the returned json widget_dict = self._get_data( url=TrendReq.GENERAL_URL, method=TrendReq.GET_METHOD, params=self.token_payload, trim_chars=4, )["widgets"] # order of the json matters... first_region_token = True # clear self.related_queries_widget_list and self.related_topics_widget_list # of old keywords'widgets self.related_queries_widget_list[:] = [] self.related_topics_widget_list[:] = [] # assign requests for widget in widget_dict: if widget["id"] == "TIMESERIES": self.interest_over_time_widget = widget if widget["id"] == "GEO_MAP" and first_region_token: self.interest_by_region_widget = widget first_region_token = False # response for each term, put into a list if "RELATED_TOPICS" in widget["id"]: self.related_topics_widget_list.append(widget) if "RELATED_QUERIES" in widget["id"]: self.related_queries_widget_list.append(widget) return def interest_over_time(self): """Request data from Google's Interest Over Time section and return a dataframe""" over_time_payload = { # convert to string as requests will mangle "req": json.dumps(self.interest_over_time_widget["request"]), "token": self.interest_over_time_widget["token"], "tz": self.tz, } # make the request and parse the returned json req_json = self._get_data( url=TrendReq.INTEREST_OVER_TIME_URL, method=TrendReq.GET_METHOD, trim_chars=5, params=over_time_payload, ) df = pd.DataFrame(req_json["default"]["timelineData"]) if df.empty: return df df["date"] = pd.to_datetime(df["time"].astype(dtype="float64"), unit="s") df = df.set_index(["date"]).sort_index() # split list columns into separate ones, remove brackets and split on comma result_df = df["value"].apply( lambda x: pd.Series(str(x).replace("[", "").replace("]", "").split(",")) ) # rename each column with its search term, relying on order that google provides... for idx, kw in enumerate(self.kw_list): # there is currently a bug with assigning columns that may be # parsed as a date in pandas: use explicit insert column method result_df.insert(len(result_df.columns), kw, result_df[idx].astype("int")) del result_df[idx] if "isPartial" in df: # make other dataframe from isPartial key data # split list columns into separate ones, remove brackets and split on comma df = df.fillna(False) result_df2 = df["isPartial"].apply( lambda x: pd.Series(str(x).replace("[", "").replace("]", "").split(",")) ) result_df2.columns = ["isPartial"] # concatenate the two dataframes final = pd.concat([result_df, result_df2], axis=1) else: final = result_df final["isPartial"] = False return final def interest_by_region( self, resolution="COUNTRY", inc_low_vol=False, inc_geo_code=False ): """Request data from Google's Interest by Region section and return a dataframe""" # make the request region_payload = dict() if self.geo == "": self.interest_by_region_widget["request"]["resolution"] = resolution elif self.geo == "US" and resolution in ["DMA", "CITY", "REGION"]: self.interest_by_region_widget["request"]["resolution"] = resolution self.interest_by_region_widget["request"][ "includeLowSearchVolumeGeos" ] = inc_low_vol # convert to string as requests will mangle region_payload["req"] = json.dumps(self.interest_by_region_widget["request"]) region_payload["token"] = self.interest_by_region_widget["token"] region_payload["tz"] = self.tz # parse returned json req_json = self._get_data( url=TrendReq.INTEREST_BY_REGION_URL, method=TrendReq.GET_METHOD, trim_chars=5, params=region_payload, ) df = pd.DataFrame(req_json["default"]["geoMapData"]) if df.empty: return df # rename the column with the search keyword df = df[["geoName", "geoCode", "value"]].set_index(["geoName"]).sort_index() # split list columns into separate ones, remove brackets and split on comma result_df = df["value"].apply( lambda x: pd.Series(str(x).replace("[", "").replace("]", "").split(",")) ) if inc_geo_code: result_df["geoCode"] = df["geoCode"] # rename each column with its search term for idx, kw in enumerate(self.kw_list): result_df[kw] = result_df[idx].astype("int") del result_df[idx] return result_df def related_topics(self): """Request data from Google's Related Topics section and return a dictionary of dataframes If no top and/or rising related topics are found, the value for the key "top" and/or "rising" will be None """ # make the request related_payload = dict() result_dict = dict() for request_json in self.related_topics_widget_list: # ensure we know which keyword we are looking at rather than relying on order kw = request_json["request"]["restriction"]["complexKeywordsRestriction"][ "keyword" ][0]["value"] # convert to string as requests will mangle related_payload["req"] = json.dumps(request_json["request"]) related_payload["token"] = request_json["token"] related_payload["tz"] = self.tz # parse the returned json req_json = self._get_data( url=TrendReq.RELATED_QUERIES_URL, method=TrendReq.GET_METHOD, trim_chars=5, params=related_payload, ) # top topics try: top_list = req_json["default"]["rankedList"][0]["rankedKeyword"] df_top = pd.DataFrame([nested_to_record(d, sep="_") for d in top_list]) except KeyError: # in case no top topics are found, the lines above will throw a KeyError df_top = None # rising topics try: rising_list = req_json["default"]["rankedList"][1]["rankedKeyword"] df_rising = pd.DataFrame( [nested_to_record(d, sep="_") for d in rising_list] ) except KeyError: # in case no rising topics are found, the lines above will throw a KeyError df_rising = None result_dict[kw] = {"rising": df_rising, "top": df_top} return result_dict def related_queries(self): """Request data from Google's Related Queries section and return a dictionary of dataframes If no top and/or rising related queries are found, the value for the key "top" and/or "rising" will be None """ # make the request related_payload = dict() result_dict = dict() for request_json in self.related_queries_widget_list: # ensure we know which keyword we are looking at rather than relying on order kw = request_json["request"]["restriction"]["complexKeywordsRestriction"][ "keyword" ][0]["value"] # convert to string as requests will mangle related_payload["req"] = json.dumps(request_json["request"]) related_payload["token"] = request_json["token"] related_payload["tz"] = self.tz # parse the returned json req_json = self._get_data( url=TrendReq.RELATED_QUERIES_URL, method=TrendReq.GET_METHOD, trim_chars=5, params=related_payload, ) # top queries try: top_df = pd.DataFrame( req_json["default"]["rankedList"][0]["rankedKeyword"] ) top_df = top_df[["query", "value"]] except KeyError: # in case no top queries are found, the lines above will throw a KeyError top_df = None # rising queries try: rising_df = pd.DataFrame( req_json["default"]["rankedList"][1]["rankedKeyword"] ) rising_df = rising_df[["query", "value"]] except KeyError: # in case no rising queries are found, the lines above will throw a KeyError rising_df = None result_dict[kw] = {"top": top_df, "rising": rising_df} return result_dict def trending_searches(self, pn="united_states"): """Request data from Google's Hot Searches section and return a dataframe""" # make the request # forms become obsolute due to the new TRENDING_SEACHES_URL # forms = {'ajax': 1, 'pn': pn, 'htd': '', 'htv': 'l'} req_json = self._get_data( url=TrendReq.TRENDING_SEARCHES_URL, method=TrendReq.GET_METHOD )[pn] result_df = pd.DataFrame(req_json) return result_df def today_searches(self, pn="US"): """Request data from Google Daily Trends section and returns a dataframe""" forms = {"ns": 15, "geo": pn, "tz": "-180", "hl": "en-US"} req_json = self._get_data( url=TrendReq.TODAY_SEARCHES_URL, method=TrendReq.GET_METHOD, trim_chars=5, params=forms, )["default"]["trendingSearchesDays"][0]["trendingSearches"] result_df = pd.DataFrame() # parse the returned json sub_df = pd.DataFrame() for trend in req_json: sub_df = sub_df.append(trend["title"], ignore_index=True) result_df = pd.concat([result_df, sub_df]) return result_df.iloc[:, -1] def top_charts(self, date, hl="en-US", tz=300, geo="GLOBAL"): """Request data from Google's Top Charts section and return a dataframe""" # create the payload chart_payload = { "hl": hl, "tz": tz, "date": date, "geo": geo, "isMobile": False, } # make the request and parse the returned json req_json = self._get_data( url=TrendReq.TOP_CHARTS_URL, method=TrendReq.GET_METHOD, trim_chars=5, params=chart_payload, )["topCharts"][0]["listItems"] df = pd.DataFrame(req_json) return df def suggestions(self, keyword): """Request data from Google's Keyword Suggestion dropdown and return a dictionary""" # make the request kw_param = quote(keyword) parameters = {"hl": self.hl} req_json = self._get_data( url=TrendReq.SUGGESTIONS_URL + kw_param, params=parameters, method=TrendReq.GET_METHOD, trim_chars=5, )["default"]["topics"] return req_json def categories(self): """Request available categories data from Google's API and return a dictionary""" params = {"hl": self.hl} req_json = self._get_data( url=TrendReq.CATEGORIES_URL, params=params, method=TrendReq.GET_METHOD, trim_chars=5, ) return req_json def get_historical_interest( self, keywords, year_start=2018, month_start=1, day_start=1, hour_start=0, year_end=2018, month_end=2, day_end=1, hour_end=0, cat=0, geo="", gprop="", sleep=0, ): """Gets historical hourly data for interest by chunking requests to 1 week at a time (which is what Google allows)""" # construct datetime obejcts - raises ValueError if invalid parameters initial_start_date = start_date = datetime( year_start, month_start, day_start, hour_start ) end_date = datetime(year_end, month_end, day_end, hour_end) # the timeframe has to be in 1 week intervals or Google will reject it delta = timedelta(days=7) df = pd.DataFrame() date_iterator = start_date date_iterator += delta while True: # format date to comply with API call start_date_str = start_date.strftime("%Y-%m-%dT%H") date_iterator_str = date_iterator.strftime("%Y-%m-%dT%H") tf = start_date_str + " " + date_iterator_str try: self.build_payload(keywords, cat, tf, geo, gprop) week_df = self.interest_over_time() df = df.append(week_df) except Exception as e: print(e) pass start_date += delta date_iterator += delta if date_iterator > end_date: # Run for 7 more days to get remaining data that would have been truncated if we stopped now # This is needed because google requires 7 days yet we may end up with a week result less than a full week start_date_str = start_date.strftime("%Y-%m-%dT%H") date_iterator_str = date_iterator.strftime("%Y-%m-%dT%H") tf = start_date_str + " " + date_iterator_str try: self.build_payload(keywords, cat, tf, geo, gprop) week_df = self.interest_over_time() df = df.append(week_df) except Exception as e: print(e) pass break # just in case you are rate-limited by Google. Recommended is 60 if you are. if sleep > 0: time.sleep(sleep) # Return the dataframe with results from our timeframe return df.loc[initial_start_date:end_date] The provided code snippet includes necessary dependencies for implementing the `google_index` function. Write a Python function `def google_index(keyword="python", start_date="2019-12-01", end_date="2019-12-04")` to solve the following problem: 返回指定区间的谷歌指数 :param keyword: :param start_date: 2019-12-10T10 :param end_date: 2019-12-10T23 :return: Here is the function: def google_index(keyword="python", start_date="2019-12-01", end_date="2019-12-04"): """ 返回指定区间的谷歌指数 :param keyword: :param start_date: 2019-12-10T10 :param end_date: 2019-12-10T23 :return: """ try: pytrends = TrendReq(hl="en-US", tz=360) kw_list = [keyword] pytrends.build_payload( kw_list, cat=0, timeframe=start_date + " " + end_date, geo="", gprop="" ) search_df = pytrends.interest_over_time() search_df['value'] = search_df[keyword] search_df['date'] = search_df.index res_df = search_df.drop(['isPartial', keyword], axis=1) return res_df except: return None
返回指定区间的谷歌指数 :param keyword: :param start_date: 2019-12-10T10 :param end_date: 2019-12-10T23 :return:
160,395
import requests from gopup.index.cons import headers from gopup.index.google_request import TrendReq from gopup.utils.date_utils import int2time def listToStr(lists): res = [] for li in lists: if not isinstance(li, list): res.append(li) if len(res) > 0: return ','.join(res) return None headers = { "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36", } def int2time(timestamp): datearr = datetime.datetime.utcfromtimestamp(timestamp) timestr = datearr.strftime("%Y-%m-%d %H:%M:%S") return timestr The provided code snippet includes necessary dependencies for implementing the `google_fact_check` function. Write a Python function `def google_fact_check(keyword, offset=0, limit=100, hl=None)` to solve the following problem: 谷歌事实查证 :param keyword: 查证关键词 :param offset: 起始数 :param limit: 每次获取数量 300篇最大 :param hl: 语言 默认为全部;中文:zh,英文:en …… :return: DataFrame title 信息标题 url 信息链接 type 查证类型 remark 查证摘要 check 查核机构 source_data 信息来源 news_img 信息图像 value 事实查证值 date 日期时间 Here is the function: def google_fact_check(keyword, offset=0, limit=100, hl=None): """ 谷歌事实查证 :param keyword: 查证关键词 :param offset: 起始数 :param limit: 每次获取数量 300篇最大 :param hl: 语言 默认为全部;中文:zh,英文:en …… :return: DataFrame title 信息标题 url 信息链接 type 查证类型 remark 查证摘要 check 查核机构 source_data 信息来源 news_img 信息图像 value 事实查证值 date 日期时间 """ try: url = "https://toolbox.google.com/factcheck/api/search" data = { "hl": hl, "query": keyword, "num_results": limit, "offset": offset } r = requests.get(url, params=data, headers=headers) if r.status_code == 200: con = r.text[6:] con = con.replace("\n", "").replace("null", "'-'") con_list = ast.literal_eval(con)[0][1] res_list = [] for i in range(0, len(con_list)): con = con_list[i] tmp = { "title": con[0][0], "type": con[0][3][0][3], "url": con[0][3][0][1], "remark": con[0][3][0][8], "check": con[0][3][0][0][0], "source_data": listToStr(con[0][3][0][0]), "date": "-" if con[0][3][0][2] == "-" else int2time(int(con[0][3][0][2])), "news_img": con[1], "value": con[2], } res_list.append(tmp) res_pd = pd.DataFrame(res_list) return res_pd except: return None
谷歌事实查证 :param keyword: 查证关键词 :param offset: 起始数 :param limit: 每次获取数量 300篇最大 :param hl: 语言 默认为全部;中文:zh,英文:en …… :return: DataFrame title 信息标题 url 信息链接 type 查证类型 remark 查证摘要 check 查核机构 source_data 信息来源 news_img 信息图像 value 事实查证值 date 日期时间
160,396
import requests from pyquery import PyQuery as pq The provided code snippet includes necessary dependencies for implementing the `station_name` function. Write a Python function `def station_name()` to solve the following problem: 获取12306车站信息 Returns ------- DataFrame "拼音码、站名、电报码、拼音、首字母、ID"" Here is the function: def station_name(): """ 获取12306车站信息 Returns ------- DataFrame "拼音码、站名、电报码、拼音、首字母、ID"" """ try: url = "https://kyfw.12306.cn/otn/resources/js/framework/station_name.js" r = requests.get(url=url) data_text = r.text tmp_str = data_text[data_text.find("='")+3: -2] tmp_list = tmp_str.split('@') res_list = [] for li in tmp_list: res_list.append(li.split('|')) columns = ["拼音码", "站名", "电报码", "拼音", "首字母", "ID"] data_df = pd.DataFrame(res_list, columns=columns) data_df.set_index("ID", inplace=True) return data_df except: return None
获取12306车站信息 Returns ------- DataFrame "拼音码、站名、电报码、拼音、首字母、ID""
160,397
import requests from pyquery import PyQuery as pq The provided code snippet includes necessary dependencies for implementing the `train_time_table` function. Write a Python function `def train_time_table(train_number)` to solve the following problem: 车次时刻表 :return: DataFrame "车次、车型、始发站、终点站、始发时、终到时、全程时间" Here is the function: def train_time_table(train_number): """ 车次时刻表 :return: DataFrame "车次、车型、始发站、终点站、始发时、终到时、全程时间" """ try: url = "https://www.keyunzhan.com/dongche/%s/" % train_number r = requests.get(url=url) doc = pq(r.text) tds = doc(".listTable td[bgcolor='#FFFFFF']") tmp = [] for v in tds.items(): tmp.append(v.text()) res = { "车次": tmp[0], "车型": tmp[1], "始发站": tmp[2], "终点站": tmp[3], "始发时": tmp[4], "终到时": tmp[5], "全程时间": tmp[6] } data_df = pd.DataFrame(res, index=[0]) return data_df except: return None
车次时刻表 :return: DataFrame "车次、车型、始发站、终点站、始发时、终到时、全程时间"
160,398
json import pandas as pd import requests The provided code snippet includes necessary dependencies for implementing the `university` function. Write a Python function `def university()` to solve the following problem: 获取全国普通高等学校名单 :return: DataFrame 序号 学校名称 学校标识码 主管部门 所在省市 所在地 办学层次 备注 Here is the function: def university(): """ 获取全国普通高等学校名单 :return: DataFrame 序号 学校名称 学校标识码 主管部门 所在省市 所在地 办学层次 备注 """ try: url = "http://img.kekepu.com/gaoxiao.json" r = requests.get(url=url) datas = json.loads(r.text) res_list = [] for data in datas: for d in datas[data]: tmp = {} tmp['序号'] = d['序号'] tmp['学校名称'] = d['学校名称'] tmp['学校标识码'] = d['学校标识码'] tmp['主管部门'] = d['主管部门'] tmp['所在省市'] = data tmp['所在地'] = d['所在地'] tmp['办学层次'] = d['办学层次'] tmp['备注'] = d['备注'] res_list.append(tmp) res_pd = pd.DataFrame(res_list) return res_pd except Exception as e: return None
获取全国普通高等学校名单 :return: DataFrame 序号 学校名称 学校标识码 主管部门 所在省市 所在地 办学层次 备注
160,399
import pandas as pd import requests The provided code snippet includes necessary dependencies for implementing the `adult_university` function. Write a Python function `def adult_university()` to solve the following problem: 获取全国成人高等学校名单 :return: DataFrame 序号 学校名称 学校标识码 主管部门 备注 Here is the function: def adult_university(): """ 获取全国成人高等学校名单 :return: DataFrame 序号 学校名称 学校标识码 主管部门 备注 """ try: url = "adult.xls" res_pd = pd.read_excel(url) return res_pd except Exception as e: return None
获取全国成人高等学校名单 :return: DataFrame 序号 学校名称 学校标识码 主管部门 备注
160,400
import time import pandas as pd from pyquery import PyQuery as pq The provided code snippet includes necessary dependencies for implementing the `club_rank` function. Write a Python function `def club_rank(type)` to solve the following problem: 中国电竞价值排行榜 俱乐部排行榜 Parameters ------ type: 类型 gameid 英雄联盟 2 绝地求生 3 王者荣耀 4 DOTA2 1 穿越火线 5 和平精英 6 Return ------ 日期、类型、排名、俱乐部logo、俱乐部名称、人气指数、舆论指数、综合指数、排名变动 http://rank.uuu9.com/club/ranking?gameId=6&type=0 Here is the function: def club_rank(type): """ 中国电竞价值排行榜 俱乐部排行榜 Parameters ------ type: 类型 gameid 英雄联盟 2 绝地求生 3 王者荣耀 4 DOTA2 1 穿越火线 5 和平精英 6 Return ------ 日期、类型、排名、俱乐部logo、俱乐部名称、人气指数、舆论指数、综合指数、排名变动 http://rank.uuu9.com/club/ranking?gameId=6&type=0 """ if type == "DOTA2": gameid = 1 elif type == "英雄联盟": gameid = 2 elif type == "绝地求生": gameid = 3 elif type == "王者荣耀": gameid = 4 elif type == "穿越火线": gameid = 5 elif type == "和平精英": gameid = 6 else: return "游戏名称输入错误" try: url = "http://rank.uuu9.com/club/ranking?gameId=%s&type=0" % gameid herder = { "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", "Accept-Language": "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3", "Accept-Encoding": "gzip, deflate", "Connection": "keep-alive" } r = requests.get(url=url, headers=herder) doc = pq(r.text) trs = doc(".ec_table table tbody tr") res_list= [] for tr in trs.items(): bd_res = tr(".ec_change i").attr("class") bd_val = tr(".ec_change").text() if bd_res == "rise": bd = "上升 %s位" % bd_val elif bd_res == "decline": bd = "下降 %s位" % bd_val else: bd = "-" res_dict = { "日期": time.strftime("%Y-%m-%d"), "类型": type, "排名": tr.find(".ec_num").text(), "俱乐部logo": "http://rank.uuu9.com/%s" % tr("img").attr("src"), "俱乐部名称": tr("dd").text(), "人气指数": tr("td:nth-child(3)").text(), "舆论指数": tr("td:nth-child(4)").text(), "综合指数": tr("td:nth-child(5)").text(), "排名变动": bd } res_list.append(res_dict) res_pd = pd.DataFrame(res_list) return res_pd except: return None
中国电竞价值排行榜 俱乐部排行榜 Parameters ------ type: 类型 gameid 英雄联盟 2 绝地求生 3 王者荣耀 4 DOTA2 1 穿越火线 5 和平精英 6 Return ------ 日期、类型、排名、俱乐部logo、俱乐部名称、人气指数、舆论指数、综合指数、排名变动 http://rank.uuu9.com/club/ranking?gameId=6&type=0
160,401
import time import pandas as pd from pyquery import PyQuery as pq The provided code snippet includes necessary dependencies for implementing the `player_rank` function. Write a Python function `def player_rank(type)` to solve the following problem: 中国电竞价值排行榜 选手排行榜 Parameters ------ type: 类型 gameid 英雄联盟 2 绝地求生 3 王者荣耀 4 DOTA2 1 穿越火线 5 和平精英 6 Return ------ 日期、类型、排名、选手头像、选手名、所属战队、人气指数、舆论指数、战绩指数、综合指数、身价、排名变动 http://rank.uuu9.com/player/ranking?gameId=6&type=0 Here is the function: def player_rank(type): """ 中国电竞价值排行榜 选手排行榜 Parameters ------ type: 类型 gameid 英雄联盟 2 绝地求生 3 王者荣耀 4 DOTA2 1 穿越火线 5 和平精英 6 Return ------ 日期、类型、排名、选手头像、选手名、所属战队、人气指数、舆论指数、战绩指数、综合指数、身价、排名变动 http://rank.uuu9.com/player/ranking?gameId=6&type=0 """ if type == "DOTA2": gameid = 1 elif type == "英雄联盟": gameid = 2 elif type == "绝地求生": gameid = 3 elif type == "王者荣耀": gameid = 4 elif type == "穿越火线": gameid = 5 elif type == "和平精英": gameid = 6 else: return "游戏名称输入错误" try: url = "http://rank.uuu9.com/player/ranking?gameId=%s&type=0" % gameid herder = { "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", "Accept-Language": "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3", "Accept-Encoding": "gzip, deflate", "Connection": "keep-alive" } r = requests.get(url=url, headers=herder) doc = pq(r.text) trs = doc(".ec_table table tbody tr") res_list= [] for tr in trs.items(): bd_res = tr(".ec_change i").attr("class") bd_val = tr(".ec_change").text() if bd_res == "rise": bd = "上升 %s位" % bd_val elif bd_res == "decline": bd = "下降 %s位" % bd_val else: bd = "-" if type == "英雄联盟": res_dict = { "日期": time.strftime("%Y-%m-%d"), "类型": type, "排名": tr.find(".ec_num").text(), "选手头像": "http://rank.uuu9.com/%s" % tr("img").attr("src"), "选手名": tr("dd").text(), "所属战队": tr("td:nth-child(3)").text(), "人气指数": tr("td:nth-child(4)").text(), "舆论指数": tr("td:nth-child(5)").text(), "战绩指数": tr("td:nth-child(6)").text(), "综合指数": tr("td:nth-child(7)").text(), "身价": tr("td:nth-child(8)").text(), "排名变动": bd } else: res_dict = { "日期": time.strftime("%Y-%m-%d"), "类型": type, "排名": tr.find(".ec_num").text(), "选手头像": "http://rank.uuu9.com/%s" % tr("img").attr("src"), "选手名": tr("dd").text(), "所属战队": tr("td:nth-child(3)").text(), "人气指数": tr("td:nth-child(4)").text(), "舆论指数": tr("td:nth-child(5)").text(), "综合指数": tr("td:nth-child(6)").text(), "身价": tr("td:nth-child(7)").text(), "排名变动": bd } res_list.append(res_dict) res_pd = pd.DataFrame(res_list) return res_pd except: return None
中国电竞价值排行榜 选手排行榜 Parameters ------ type: 类型 gameid 英雄联盟 2 绝地求生 3 王者荣耀 4 DOTA2 1 穿越火线 5 和平精英 6 Return ------ 日期、类型、排名、选手头像、选手名、所属战队、人气指数、舆论指数、战绩指数、综合指数、身价、排名变动 http://rank.uuu9.com/player/ranking?gameId=6&type=0
160,402
import requests from tqdm import tqdm from pyquery import PyQuery as pq def _get_page_num_charity_organization(): """ 慈善中国-慈善组织查询-总页数 :return: 总页数 """ url = "http://cishan.chinanpo.gov.cn/biz/ma/csmh/a/csmhaDoSort.html" payload_params = { "aaee0102_03": "", "field": "aaex0131", "sort": "desc", "flag": "0", } payload_data = {"pageNo": "1"} r = requests.post(url, params=payload_params, data=payload_data) pages = r.text[r.text.find("第1页/共") + 5: r.text.rfind("页</font>")] return int(pages) The provided code snippet includes necessary dependencies for implementing the `charity_organization` function. Write a Python function `def charity_organization()` to solve the following problem: 慈善中国-慈善组织查询 http://cishan.chinanpo.gov.cn/biz/ma/csmh/a/csmhaindex.html :return: 慈善中国-慈善组织查询 :rtype: pandas.DataFrame Here is the function: def charity_organization(): """ 慈善中国-慈善组织查询 http://cishan.chinanpo.gov.cn/biz/ma/csmh/a/csmhaindex.html :return: 慈善中国-慈善组织查询 :rtype: pandas.DataFrame """ page_num = _get_page_num_charity_organization() url = "http://cishan.chinanpo.gov.cn/biz/ma/csmh/a/csmhaDoSort.html" params = { "field": "aaex0131", "sort": "desc", "flag": "0", } outer_df = pd.DataFrame() for page in tqdm(range(1, page_num+1)): # page = 1 params["pageNo"] = str(page) r = requests.post(url, params=params) inner_df = pd.read_html(r.text)[0] outer_df = outer_df.append(inner_df, ignore_index=True) return outer_df
慈善中国-慈善组织查询 http://cishan.chinanpo.gov.cn/biz/ma/csmh/a/csmhaindex.html :return: 慈善中国-慈善组织查询 :rtype: pandas.DataFrame
160,403
json import pandas as pd import requests The provided code snippet includes necessary dependencies for implementing the `energy_oil_hist` function. Write a Python function `def energy_oil_hist()` to solve the following problem: 汽柴油历史调价信息 http://data.eastmoney.com/cjsj/oil_default.html :return: 汽柴油历史调价数 :rtype: pandas.DataFrame Here is the function: def energy_oil_hist(): """ 汽柴油历史调价信息 http://data.eastmoney.com/cjsj/oil_default.html :return: 汽柴油历史调价数 :rtype: pandas.DataFrame """ try: url = "http://datacenter.eastmoney.com/api/data/get" params = { "type": "RPTA_WEB_YJ_BD", "sty": "ALL", "source": "WEB", "p": "1", "ps": "5000", "st": "dim_date", "sr": "-1", "var": "OxGINxug", "rt": "52861006", } r = requests.get(url, params=params) data_text = r.text data_json = json.loads(data_text[data_text.find("{"): -1]) data_df = pd.DataFrame(data_json["result"]["data"]) data_df.columns = ["日期", "汽油价格", "柴油价格", "汽油涨幅", "柴油涨幅"] return data_df except: return None
汽柴油历史调价信息 http://data.eastmoney.com/cjsj/oil_default.html :return: 汽柴油历史调价数 :rtype: pandas.DataFrame
160,404
json import pandas as pd import requests The provided code snippet includes necessary dependencies for implementing the `energy_oil_detail` function. Write a Python function `def energy_oil_detail(date="2020-03-19")` to solve the following problem: 地区油价 http://data.eastmoney.com/cjsj/oil_default.html :param date: :type date: str :return: 地区油价 :rtype: pandas.DataFrame Here is the function: def energy_oil_detail(date="2020-03-19"): """ 地区油价 http://data.eastmoney.com/cjsj/oil_default.html :param date: :type date: str :return: 地区油价 :rtype: pandas.DataFrame """ try: url = "http://datacenter.eastmoney.com/api/data/get" params = { "type": "RPTA_WEB_YJ_JH", "sty": "ALL", "source": "WEB", "p": "1", "ps": "5000", "st": "cityname", "sr": "1", "filter": f'(dim_date="{date}")', "var": "todayPriceData", } r = requests.get(url, params=params) data_text = r.text data_json = json.loads(data_text[data_text.find("{"): -1]) data_df = pd.DataFrame(data_json["result"]["data"]).iloc[:, 1:] return data_df except: return None
地区油价 http://data.eastmoney.com/cjsj/oil_default.html :param date: :type date: str :return: 地区油价 :rtype: pandas.DataFrame
160,405
from gopup.pro import client from gopup.utils import utils_pass The provided code snippet includes necessary dependencies for implementing the `pro_api` function. Write a Python function `def pro_api(token='', timeout=30)` to solve the following problem: 初始化pro API, 第一次可以通过gp.set_token('your token')来记录自己的token凭证, 临时token可以通过本参数传入 Here is the function: def pro_api(token='', timeout=30): """ 初始化pro API, 第一次可以通过gp.set_token('your token')来记录自己的token凭证, 临时token可以通过本参数传入 """ if token == '' or token is None: token = utils_pass.get_token() if token is not None and token != '': pro = client.DataApi(token=token, timeout=timeout) return pro else: raise Exception('api init error.')
初始化pro API, 第一次可以通过gp.set_token('your token')来记录自己的token凭证, 临时token可以通过本参数传入
160,406
json import pandas as pd import requests The provided code snippet includes necessary dependencies for implementing the `douban_movie_list` function. Write a Python function `def douban_movie_list()` to solve the following problem: 豆瓣新片榜 Returns ------- DataFrame "titleCn, title,rate, link, img, description, ranking" Here is the function: def douban_movie_list(): """ 豆瓣新片榜 Returns ------- DataFrame "titleCn, title,rate, link, img, description, ranking" """ try: url = "https://www.bjsoubang.com/api/getChannelData" params = { "channel_id": 16 } r = requests.get(url=url, params=params) res_list = json.loads(r.text)['info']['data'] df = pd.DataFrame(res_list) df['ranking'] = df.index + 1 return df except: return None
豆瓣新片榜 Returns ------- DataFrame "titleCn, title,rate, link, img, description, ranking"
160,407
json import pandas as pd import requests The provided code snippet includes necessary dependencies for implementing the `douban_week_praise_list` function. Write a Python function `def douban_week_praise_list()` to solve the following problem: 豆瓣一周口碑榜 Returns ------- DataFrame "title,trend, link, ranking" Here is the function: def douban_week_praise_list(): """ 豆瓣一周口碑榜 Returns ------- DataFrame "title,trend, link, ranking" """ try: url = "https://www.bjsoubang.com/api/getChannelData" params = { "channel_id": 19 } r = requests.get(url=url, params=params) res_list = json.loads(r.text)['info']['data'] df = pd.DataFrame(res_list) return df except: return None
豆瓣一周口碑榜 Returns ------- DataFrame "title,trend, link, ranking"
160,408
json import pandas as pd import requests The provided code snippet includes necessary dependencies for implementing the `zhihu_hot_search_list` function. Write a Python function `def zhihu_hot_search_list()` to solve the following problem: 知乎热搜榜 Returns ------- DataFrame "display_query,query, link, ranking" Here is the function: def zhihu_hot_search_list(): """ 知乎热搜榜 Returns ------- DataFrame "display_query,query, link, ranking" """ try: url = "https://www.bjsoubang.com/api/getChannelData" params = { "channel_id": 10 } r = requests.get(url=url, params=params) res_list = json.loads(r.text)['info']['data'] df = pd.DataFrame(res_list) df['ranking'] = df.index + 1 return df except: return None
知乎热搜榜 Returns ------- DataFrame "display_query,query, link, ranking"
160,409
json import pandas as pd import requests The provided code snippet includes necessary dependencies for implementing the `zhihu_hot_list` function. Write a Python function `def zhihu_hot_list()` to solve the following problem: 知乎热榜 Returns ------- DataFrame "title, img,description, link, ranking, hot" Here is the function: def zhihu_hot_list(): """ 知乎热榜 Returns ------- DataFrame "title, img,description, link, ranking, hot" """ try: url = "https://www.bjsoubang.com/api/getChannelData" params = { "channel_id": 2 } r = requests.get(url=url, params=params) res_list = json.loads(r.text)['info']['data'] df = pd.DataFrame(res_list) df['ranking'] = df.index + 1 return df except: return None
知乎热榜 Returns ------- DataFrame "title, img,description, link, ranking, hot"
160,410
json import pandas as pd import requests The provided code snippet includes necessary dependencies for implementing the `wx_hot_word_list` function. Write a Python function `def wx_hot_word_list()` to solve the following problem: 微信热词榜 Returns ------- DataFrame "title, link, hot_rank, ranking" Here is the function: def wx_hot_word_list(): """ 微信热词榜 Returns ------- DataFrame "title, link, hot_rank, ranking" """ try: url = "https://www.bjsoubang.com/api/getChannelData" params = { "channel_id": 6 } r = requests.get(url=url, params=params) res_list = json.loads(r.text)['info']['data'] df = pd.DataFrame(res_list) df['ranking'] = df.index + 1 return df except: return None
微信热词榜 Returns ------- DataFrame "title, link, hot_rank, ranking"
160,411
json import pandas as pd import requests The provided code snippet includes necessary dependencies for implementing the `wx_hot_list` function. Write a Python function `def wx_hot_list()` to solve the following problem: 微信热门榜 Returns ------- DataFrame "title, img,description, link, ranking" Here is the function: def wx_hot_list(): """ 微信热门榜 Returns ------- DataFrame "title, img,description, link, ranking" """ try: url = "https://www.bjsoubang.com/api/getChannelData" params = { "channel_id": 1 } r = requests.get(url=url, params=params) res_list = json.loads(r.text)['info']['data'] df = pd.DataFrame(res_list) df['ranking'] = df.index + 1 return df except: return None
微信热门榜 Returns ------- DataFrame "title, img,description, link, ranking"
160,412
json import pandas as pd import requests The provided code snippet includes necessary dependencies for implementing the `weibo_hot_search_list` function. Write a Python function `def weibo_hot_search_list()` to solve the following problem: 微博热搜榜 Returns ------- DataFrame "title, tag, link, hot, ranking" Here is the function: def weibo_hot_search_list(): """ 微博热搜榜 Returns ------- DataFrame "title, tag, link, hot, ranking" """ try: url = "https://www.bjsoubang.com/api/getChannelData" params = { "channel_id": 4 } r = requests.get(url=url, params=params) res_list = json.loads(r.text)['info']['data'] df = pd.DataFrame(res_list) df['ranking'] = df.index + 1 return df except: return None
微博热搜榜 Returns ------- DataFrame "title, tag, link, hot, ranking"
160,413
json import pandas as pd import requests The provided code snippet includes necessary dependencies for implementing the `weibo_new_era_list` function. Write a Python function `def weibo_new_era_list()` to solve the following problem: 微博新时代榜 Returns ------- DataFrame "title, link, ranking" Here is the function: def weibo_new_era_list(): """ 微博新时代榜 Returns ------- DataFrame "title, link, ranking" """ try: url = "https://www.bjsoubang.com/api/getChannelData" params = { "channel_id": 5 } r = requests.get(url=url, params=params) res_list = json.loads(r.text)['info']['data'] df = pd.DataFrame(res_list) df['ranking'] = df.index + 1 return df except: return None
微博新时代榜 Returns ------- DataFrame "title, link, ranking"
160,414
json import pandas as pd import requests The provided code snippet includes necessary dependencies for implementing the `baidu_hot_list` function. Write a Python function `def baidu_hot_list()` to solve the following problem: 百度实时热点榜 Returns ------- DataFrame "title, id, status, link_video, link_search, link_news, link_img, hot, ranking" Here is the function: def baidu_hot_list(): """ 百度实时热点榜 Returns ------- DataFrame "title, id, status, link_video, link_search, link_news, link_img, hot, ranking" """ try: url = "https://www.bjsoubang.com/api/getChannelData" params = { "channel_id": 3 } r = requests.get(url=url, params=params) res_list = json.loads(r.text)['info']['data'] df = pd.DataFrame(res_list) df['ranking'] = df.index + 1 return df except: return None
百度实时热点榜 Returns ------- DataFrame "title, id, status, link_video, link_search, link_news, link_img, hot, ranking"
160,415
json import pandas as pd import requests The provided code snippet includes necessary dependencies for implementing the `baidu_today_hot_list` function. Write a Python function `def baidu_today_hot_list()` to solve the following problem: 百度今日热点榜 Returns ------- DataFrame "title, id, status, link_video, link_search, link_news, link_img, hot, ranking" Here is the function: def baidu_today_hot_list(): """ 百度今日热点榜 Returns ------- DataFrame "title, id, status, link_video, link_search, link_news, link_img, hot, ranking" """ try: url = "https://www.bjsoubang.com/api/getChannelData" params = { "channel_id": 12 } r = requests.get(url=url, params=params) res_list = json.loads(r.text)['info']['data'] df = pd.DataFrame(res_list) df['ranking'] = df.index + 1 return df except: return None
百度今日热点榜 Returns ------- DataFrame "title, id, status, link_video, link_search, link_news, link_img, hot, ranking"
160,416
json import pandas as pd import requests The provided code snippet includes necessary dependencies for implementing the `baidu_hot_word_list` function. Write a Python function `def baidu_hot_word_list()` to solve the following problem: 百度百科热词榜 Returns ------- DataFrame "title, link, status, description, ranking" Here is the function: def baidu_hot_word_list(): """ 百度百科热词榜 Returns ------- DataFrame "title, link, status, description, ranking" """ try: url = "https://www.bjsoubang.com/api/getChannelData" params = { "channel_id": 9 } r = requests.get(url=url, params=params) res_list = json.loads(r.text)['info']['data'] df = pd.DataFrame(res_list) df['ranking'] = df.index + 1 return df except: return None
百度百科热词榜 Returns ------- DataFrame "title, link, status, description, ranking"
160,417
requests import pandas as pd from gopup.event.cons import province_dict, city_dict city_dict = { "520300": "遵义市", "510300": "自贡市", "370300": "淄博市", "512000": "资阳市", "411700": "驻马店市", "430200": "株洲市", "440400": "珠海市", "411600": "周口市", "330900": "舟山市", "500100": "重庆市", "500200": "重庆市", "640500": "中卫市", "442000": "中山市", "410100": "郑州市", "321100": "镇江市", "441200": "肇庆市", "530600": "昭通市", "140400": "长治市", "430100": "长沙市", "220100": "长春市", "350600": "漳州市", "719007": "彰化县", "620700": "张掖市", "130700": "张家口市", "430800": "张家界市", "440800": "湛江市", "370400": "枣庄市", "140800": "运城市", "719008": "云林县", "445300": "云浮市", "430600": "岳阳市", "530400": "玉溪市", "632700": "玉树藏族自治州", "450900": "玉林市", "610800": "榆林市", "431100": "永州市", "210800": "营口市", "360600": "鹰潭市", "640100": "银川市", "430900": "益阳市", "719005": "宜兰县", "360900": "宜春市", "420500": "宜昌市", "511500": "宜宾市", "654000": "伊犁哈萨克自治州", "230700": "伊春市", "140300": "阳泉市", "441700": "阳江市", "321000": "扬州市", "320900": "盐城市", "222400": "延边朝鲜族自治州", "610600": "延安市", "370600": "烟台市", "511800": "雅安市", "341800": "宣城市", "411000": "许昌市", "320300": "徐州市", "341300": "宿州市", "321300": "宿迁市", "152200": "兴安盟", "130500": "邢台市", "411500": "信阳市", "719004": "新竹县", "719002": "新竹市", "360500": "新余市", "410700": "新乡市", "710300": "新北市", "140900": "忻州市", "420900": "孝感市", "420600": "襄阳市", "433100": "湘西土家族苗族自治州", "430300": "湘潭市", "810000": "香港", "610400": "咸阳市", "421200": "咸宁市", "429004": "仙桃市", "152500": "锡林郭勒盟", "532800": "西双版纳傣族自治州", "630100": "西宁市", "610100": "西安市", "620600": "武威市", "420100": "武汉市", "469001": "五指山市", "659004": "五家渠市", "450400": "梧州市", "640300": "吴忠市", "340200": "芜湖市", "320200": "无锡市", "650100": "乌鲁木齐市", "150900": "乌兰察布市", "150300": "乌海市", "532600": "文山壮族苗族自治州", "469005": "文昌市", "330300": "温州市", "610500": "渭南市", "370700": "潍坊市", "371000": "威海市", "469006": "万宁市", "469022": "屯昌县", "650400": "吐鲁番市", "659003": "图木舒克市", "520600": "铜仁市", "340700": "铜陵市", "610200": "铜川市", "150500": "通辽市", "220500": "通化市", "659006": "铁门关市", "211200": "铁岭市", "620500": "天水市", "429006": "天门市", "120100": "天津市", "710600": "桃园市", "130200": "唐山市", "321200": "泰州市", "370900": "泰安市", "140100": "太原市", "331000": "台州市", "710400": "台中市", "710500": "台南市", "719012": "台东县", "710100": "台北市", "654200": "塔城地区", "510900": "遂宁市", "421300": "随州市", "231200": "绥化市", "320500": "苏州市", "220700": "松原市", "220300": "四平市", "140600": "朔州市", "230500": "双鸭山市", "659007": "双河市", "640200": "石嘴山市", "130100": "石家庄市", "659001": "石河子市", "420300": "十堰市", "210100": "沈阳市", "429021": "神农架林区", "440300": "深圳市", "330600": "绍兴市", "430500": "邵阳市", "440200": "韶关市", "361100": "上饶市", "310100": "上海市", "411400": "商丘市", "611000": "商洛市", "441500": "汕尾市", "440500": "汕头市", "540500": "山南市", "350200": "厦门市", "460200": "三亚市", "460300": "三沙市", "350400": "三明市", "411200": "三门峡市", "371100": "日照市", "540200": "日喀则市", "350500": "泉州市", "530300": "曲靖市", "330800": "衢州市", "469030": "琼中黎族苗族自治县", "469002": "琼海市", "621000": "庆阳市", "441800": "清远市", "370200": "青岛市", "130300": "秦皇岛市", "450700": "钦州市", "522300": "黔西南布依族苗族自治州", "522700": "黔南布依族苗族自治州", "522600": "黔东南苗族侗族自治州", "429005": "潜江市", "230200": "齐齐哈尔市", "230900": "七台河市", "530800": "普洱市", "410900": "濮阳市", "350300": "莆田市", "360300": "萍乡市", "719011": "屏东县", "620800": "平凉市", "410400": "平顶山市", "719014": "澎湖县", "211100": "盘锦市", "510400": "攀枝花市", "533300": "怒江傈僳族自治州", "350900": "宁德市", "330200": "宁波市", "511000": "内江市", "411300": "南阳市", "719009": "南投县", "320600": "南通市", "350700": "南平市", "450100": "南宁市", "320100": "南京市", "511300": "南充市", "360100": "南昌市", "540600": "那曲市", "231000": "牡丹江市", "719006": "苗栗县", "510700": "绵阳市", "441400": "梅州市", "511400": "眉山市", "440900": "茂名市", "340500": "马鞍山市", "141100": "吕梁市", "411100": "漯河市", "410300": "洛阳市", "510500": "泸州市", "431300": "娄底市", "621200": "陇南市", "350800": "龙岩市", "520200": "六盘水市", "341500": "六安市", "450200": "柳州市", "469028": "陵水黎族自治县", "371300": "临沂市", "622900": "临夏回族自治州", "469024": "临高县", "141000": "临汾市", "530900": "临沧市", "540400": "林芝市", "371500": "聊城市", "220400": "辽源市", "211000": "辽阳市", "513400": "凉山彝族自治州", "320700": "连云港市", "331100": "丽水市", "530700": "丽江市", "511100": "乐山市", "469027": "乐东黎族自治县", "131000": "廊坊市", "620100": "兰州市", "451300": "来宾市", "540100": "拉萨市", "659009": "昆玉市", "530100": "昆明市", "653000": "克孜勒苏柯尔克孜自治州", "650200": "克拉玛依市", "659008": "可克达拉市", "410200": "开封市", "653100": "喀什地区", "620900": "酒泉市", "360400": "九江市", "360200": "景德镇市", "421000": "荆州市", "420800": "荆门市", "140700": "晋中市", "140500": "晋城市", "210700": "锦州市", "330700": "金华市", "620300": "金昌市", "445200": "揭阳市", "410800": "焦作市", "440700": "江门市", "620200": "嘉峪关市", "719010": "嘉义县", "719003": "嘉义市", "330400": "嘉兴市", "230800": "佳木斯市", "419001": "济源市", "370800": "济宁市", "370100": "济南市", "220200": "吉林市", "360800": "吉安市", "719001": "基隆市", "230300": "鸡西市", "441300": "惠州市", "420200": "黄石市", "341000": "黄山市", "632300": "黄南藏族自治州", "421100": "黄冈市", "340400": "淮南市", "340600": "淮北市", "320800": "淮安市", "431200": "怀化市", "719013": "花莲县", "330500": "湖州市", "211400": "葫芦岛市", "150700": "呼伦贝尔市", "150100": "呼和浩特市", "532500": "红河哈尼族彝族自治州", "430400": "衡阳市", "131100": "衡水市", "231100": "黑河市", "230400": "鹤岗市", "410600": "鹤壁市", "451100": "贺州市", "371700": "菏泽市", "441600": "河源市", "451200": "河池市", "653200": "和田地区", "340100": "合肥市", "330100": "杭州市", "610700": "汉中市", "130400": "邯郸市", "632800": "海西蒙古族藏族自治州", "632500": "海南藏族自治州", "460100": "海口市", "630200": "海东市", "632200": "海北藏族自治州", "650500": "哈密市", "230100": "哈尔滨市", "632600": "果洛藏族自治州", "450300": "桂林市", "520100": "贵阳市", "450800": "贵港市", "440100": "广州市", "510800": "广元市", "511600": "广安市", "640400": "固原市", "710200": "高雄市", "360700": "赣州市", "513300": "甘孜藏族自治州", "623000": "甘南藏族自治州", "341200": "阜阳市", "210900": "阜新市", "361000": "抚州市", "210400": "抚顺市", "350100": "福州市", "440600": "佛山市", "450600": "防城港市", "422800": "恩施土家族苗族自治州", "420700": "鄂州市", "150600": "鄂尔多斯市", "370500": "东营市", "441900": "东莞市", "469007": "东方市", "621100": "定西市", "469021": "定安县", "533400": "迪庆藏族自治州", "371400": "德州市", "510600": "德阳市", "533100": "德宏傣族景颇族自治州", "460400": "儋州市", "210600": "丹东市", "232700": "大兴安岭地区", "140200": "大同市", "230600": "大庆市", "210200": "大连市", "532900": "大理白族自治州", "511700": "达州市", "532300": "楚雄彝族自治州", "341100": "滁州市", "451400": "崇左市", "150400": "赤峰市", "341700": "池州市", "469023": "澄迈县", "130800": "承德市", "510100": "成都市", "431000": "郴州市", "445100": "潮州市", "211300": "朝阳市", "320400": "常州市", "430700": "常德市", "469026": "昌江黎族自治县", "652300": "昌吉回族自治州", "540300": "昌都市", "130900": "沧州市", "652700": "博尔塔拉蒙古自治州", "341600": "亳州市", "371600": "滨州市", "520500": "毕节市", "210500": "本溪市", "659005": "北屯市", "110100": "北京市", "450500": "北海市", "469029": "保亭黎族苗族自治县", "530500": "保山市", "130600": "保定市", "610300": "宝鸡市", "150200": "包头市", "340300": "蚌埠市", "451000": "百色市", "620400": "白银市", "220600": "白山市", "469025": "白沙黎族自治县", "220800": "白城市", "511900": "巴中市", "652800": "巴音郭楞蒙古自治州", "150800": "巴彦淖尔市", "820000": "澳门", "210300": "鞍山市", "410500": "安阳市", "520400": "安顺市", "340800": "安庆市", "610900": "安康市", "542500": "阿里地区", "654300": "阿勒泰地区", "152900": "阿拉善盟", "659002": "阿拉尔市", "652900": "阿克苏地区", "513200": "阿坝藏族羌族自治州", } The provided code snippet includes necessary dependencies for implementing the `migration_area_baidu` function. Write a Python function `def migration_area_baidu(area="武汉市", indicator="move_in", date="20200201")` to solve the following problem: 百度地图慧眼-百度迁徙-XXX迁入地详情 百度地图慧眼-百度迁徙-XXX迁出地详情 以上展示 top100 结果,如不够 100 则展示全部 迁入来源地比例: 从 xx 地迁入到当前区域的人数与当前区域迁入总人口的比值 迁出目的地比例: 从当前区域迁出到 xx 的人口与从当前区域迁出总人口的比值 https://qianxi.baidu.com/?from=shoubai#city=0 :param area: 可以输入 省份 或者 具体城市 但是需要用全称 :type area: str :param indicator: move_in 迁入 move_out 迁出 :type indicator: str :param date: 查询的日期 20200101以后的时间 :type date: str :return: 迁入地详情/迁出地详情的前50个 :rtype: pandas.DataFrame Here is the function: def migration_area_baidu(area="武汉市", indicator="move_in", date="20200201"): """ 百度地图慧眼-百度迁徙-XXX迁入地详情 百度地图慧眼-百度迁徙-XXX迁出地详情 以上展示 top100 结果,如不够 100 则展示全部 迁入来源地比例: 从 xx 地迁入到当前区域的人数与当前区域迁入总人口的比值 迁出目的地比例: 从当前区域迁出到 xx 的人口与从当前区域迁出总人口的比值 https://qianxi.baidu.com/?from=shoubai#city=0 :param area: 可以输入 省份 或者 具体城市 但是需要用全称 :type area: str :param indicator: move_in 迁入 move_out 迁出 :type indicator: str :param date: 查询的日期 20200101以后的时间 :type date: str :return: 迁入地详情/迁出地详情的前50个 :rtype: pandas.DataFrame """ try: if area == "全国": payload = { "dt": "country", "id": 0, "type": indicator, "date": date, } else: city_dict.update(province_dict) inner_dict = dict(zip(city_dict.values(), city_dict.keys())) if inner_dict[area] in province_dict.keys(): dt_flag = "province" else: dt_flag = "city" payload = { "dt": dt_flag, "id": inner_dict[area], "type": indicator, "date": date, } url = "https://huiyan.baidu.com/migration/cityrank.jsonp" r = requests.get(url, params=payload) json_data = json.loads(r.text[r.text.find("({") + 1 : r.text.rfind(");")]) return pd.DataFrame(json_data["data"]["list"]) except: return None
百度地图慧眼-百度迁徙-XXX迁入地详情 百度地图慧眼-百度迁徙-XXX迁出地详情 以上展示 top100 结果,如不够 100 则展示全部 迁入来源地比例: 从 xx 地迁入到当前区域的人数与当前区域迁入总人口的比值 迁出目的地比例: 从当前区域迁出到 xx 的人口与从当前区域迁出总人口的比值 https://qianxi.baidu.com/?from=shoubai#city=0 :param area: 可以输入 省份 或者 具体城市 但是需要用全称 :type area: str :param indicator: move_in 迁入 move_out 迁出 :type indicator: str :param date: 查询的日期 20200101以后的时间 :type date: str :return: 迁入地详情/迁出地详情的前50个 :rtype: pandas.DataFrame
160,418
requests import pandas as pd from gopup.event.cons import province_dict, city_dict city_dict = { "520300": "遵义市", "510300": "自贡市", "370300": "淄博市", "512000": "资阳市", "411700": "驻马店市", "430200": "株洲市", "440400": "珠海市", "411600": "周口市", "330900": "舟山市", "500100": "重庆市", "500200": "重庆市", "640500": "中卫市", "442000": "中山市", "410100": "郑州市", "321100": "镇江市", "441200": "肇庆市", "530600": "昭通市", "140400": "长治市", "430100": "长沙市", "220100": "长春市", "350600": "漳州市", "719007": "彰化县", "620700": "张掖市", "130700": "张家口市", "430800": "张家界市", "440800": "湛江市", "370400": "枣庄市", "140800": "运城市", "719008": "云林县", "445300": "云浮市", "430600": "岳阳市", "530400": "玉溪市", "632700": "玉树藏族自治州", "450900": "玉林市", "610800": "榆林市", "431100": "永州市", "210800": "营口市", "360600": "鹰潭市", "640100": "银川市", "430900": "益阳市", "719005": "宜兰县", "360900": "宜春市", "420500": "宜昌市", "511500": "宜宾市", "654000": "伊犁哈萨克自治州", "230700": "伊春市", "140300": "阳泉市", "441700": "阳江市", "321000": "扬州市", "320900": "盐城市", "222400": "延边朝鲜族自治州", "610600": "延安市", "370600": "烟台市", "511800": "雅安市", "341800": "宣城市", "411000": "许昌市", "320300": "徐州市", "341300": "宿州市", "321300": "宿迁市", "152200": "兴安盟", "130500": "邢台市", "411500": "信阳市", "719004": "新竹县", "719002": "新竹市", "360500": "新余市", "410700": "新乡市", "710300": "新北市", "140900": "忻州市", "420900": "孝感市", "420600": "襄阳市", "433100": "湘西土家族苗族自治州", "430300": "湘潭市", "810000": "香港", "610400": "咸阳市", "421200": "咸宁市", "429004": "仙桃市", "152500": "锡林郭勒盟", "532800": "西双版纳傣族自治州", "630100": "西宁市", "610100": "西安市", "620600": "武威市", "420100": "武汉市", "469001": "五指山市", "659004": "五家渠市", "450400": "梧州市", "640300": "吴忠市", "340200": "芜湖市", "320200": "无锡市", "650100": "乌鲁木齐市", "150900": "乌兰察布市", "150300": "乌海市", "532600": "文山壮族苗族自治州", "469005": "文昌市", "330300": "温州市", "610500": "渭南市", "370700": "潍坊市", "371000": "威海市", "469006": "万宁市", "469022": "屯昌县", "650400": "吐鲁番市", "659003": "图木舒克市", "520600": "铜仁市", "340700": "铜陵市", "610200": "铜川市", "150500": "通辽市", "220500": "通化市", "659006": "铁门关市", "211200": "铁岭市", "620500": "天水市", "429006": "天门市", "120100": "天津市", "710600": "桃园市", "130200": "唐山市", "321200": "泰州市", "370900": "泰安市", "140100": "太原市", "331000": "台州市", "710400": "台中市", "710500": "台南市", "719012": "台东县", "710100": "台北市", "654200": "塔城地区", "510900": "遂宁市", "421300": "随州市", "231200": "绥化市", "320500": "苏州市", "220700": "松原市", "220300": "四平市", "140600": "朔州市", "230500": "双鸭山市", "659007": "双河市", "640200": "石嘴山市", "130100": "石家庄市", "659001": "石河子市", "420300": "十堰市", "210100": "沈阳市", "429021": "神农架林区", "440300": "深圳市", "330600": "绍兴市", "430500": "邵阳市", "440200": "韶关市", "361100": "上饶市", "310100": "上海市", "411400": "商丘市", "611000": "商洛市", "441500": "汕尾市", "440500": "汕头市", "540500": "山南市", "350200": "厦门市", "460200": "三亚市", "460300": "三沙市", "350400": "三明市", "411200": "三门峡市", "371100": "日照市", "540200": "日喀则市", "350500": "泉州市", "530300": "曲靖市", "330800": "衢州市", "469030": "琼中黎族苗族自治县", "469002": "琼海市", "621000": "庆阳市", "441800": "清远市", "370200": "青岛市", "130300": "秦皇岛市", "450700": "钦州市", "522300": "黔西南布依族苗族自治州", "522700": "黔南布依族苗族自治州", "522600": "黔东南苗族侗族自治州", "429005": "潜江市", "230200": "齐齐哈尔市", "230900": "七台河市", "530800": "普洱市", "410900": "濮阳市", "350300": "莆田市", "360300": "萍乡市", "719011": "屏东县", "620800": "平凉市", "410400": "平顶山市", "719014": "澎湖县", "211100": "盘锦市", "510400": "攀枝花市", "533300": "怒江傈僳族自治州", "350900": "宁德市", "330200": "宁波市", "511000": "内江市", "411300": "南阳市", "719009": "南投县", "320600": "南通市", "350700": "南平市", "450100": "南宁市", "320100": "南京市", "511300": "南充市", "360100": "南昌市", "540600": "那曲市", "231000": "牡丹江市", "719006": "苗栗县", "510700": "绵阳市", "441400": "梅州市", "511400": "眉山市", "440900": "茂名市", "340500": "马鞍山市", "141100": "吕梁市", "411100": "漯河市", "410300": "洛阳市", "510500": "泸州市", "431300": "娄底市", "621200": "陇南市", "350800": "龙岩市", "520200": "六盘水市", "341500": "六安市", "450200": "柳州市", "469028": "陵水黎族自治县", "371300": "临沂市", "622900": "临夏回族自治州", "469024": "临高县", "141000": "临汾市", "530900": "临沧市", "540400": "林芝市", "371500": "聊城市", "220400": "辽源市", "211000": "辽阳市", "513400": "凉山彝族自治州", "320700": "连云港市", "331100": "丽水市", "530700": "丽江市", "511100": "乐山市", "469027": "乐东黎族自治县", "131000": "廊坊市", "620100": "兰州市", "451300": "来宾市", "540100": "拉萨市", "659009": "昆玉市", "530100": "昆明市", "653000": "克孜勒苏柯尔克孜自治州", "650200": "克拉玛依市", "659008": "可克达拉市", "410200": "开封市", "653100": "喀什地区", "620900": "酒泉市", "360400": "九江市", "360200": "景德镇市", "421000": "荆州市", "420800": "荆门市", "140700": "晋中市", "140500": "晋城市", "210700": "锦州市", "330700": "金华市", "620300": "金昌市", "445200": "揭阳市", "410800": "焦作市", "440700": "江门市", "620200": "嘉峪关市", "719010": "嘉义县", "719003": "嘉义市", "330400": "嘉兴市", "230800": "佳木斯市", "419001": "济源市", "370800": "济宁市", "370100": "济南市", "220200": "吉林市", "360800": "吉安市", "719001": "基隆市", "230300": "鸡西市", "441300": "惠州市", "420200": "黄石市", "341000": "黄山市", "632300": "黄南藏族自治州", "421100": "黄冈市", "340400": "淮南市", "340600": "淮北市", "320800": "淮安市", "431200": "怀化市", "719013": "花莲县", "330500": "湖州市", "211400": "葫芦岛市", "150700": "呼伦贝尔市", "150100": "呼和浩特市", "532500": "红河哈尼族彝族自治州", "430400": "衡阳市", "131100": "衡水市", "231100": "黑河市", "230400": "鹤岗市", "410600": "鹤壁市", "451100": "贺州市", "371700": "菏泽市", "441600": "河源市", "451200": "河池市", "653200": "和田地区", "340100": "合肥市", "330100": "杭州市", "610700": "汉中市", "130400": "邯郸市", "632800": "海西蒙古族藏族自治州", "632500": "海南藏族自治州", "460100": "海口市", "630200": "海东市", "632200": "海北藏族自治州", "650500": "哈密市", "230100": "哈尔滨市", "632600": "果洛藏族自治州", "450300": "桂林市", "520100": "贵阳市", "450800": "贵港市", "440100": "广州市", "510800": "广元市", "511600": "广安市", "640400": "固原市", "710200": "高雄市", "360700": "赣州市", "513300": "甘孜藏族自治州", "623000": "甘南藏族自治州", "341200": "阜阳市", "210900": "阜新市", "361000": "抚州市", "210400": "抚顺市", "350100": "福州市", "440600": "佛山市", "450600": "防城港市", "422800": "恩施土家族苗族自治州", "420700": "鄂州市", "150600": "鄂尔多斯市", "370500": "东营市", "441900": "东莞市", "469007": "东方市", "621100": "定西市", "469021": "定安县", "533400": "迪庆藏族自治州", "371400": "德州市", "510600": "德阳市", "533100": "德宏傣族景颇族自治州", "460400": "儋州市", "210600": "丹东市", "232700": "大兴安岭地区", "140200": "大同市", "230600": "大庆市", "210200": "大连市", "532900": "大理白族自治州", "511700": "达州市", "532300": "楚雄彝族自治州", "341100": "滁州市", "451400": "崇左市", "150400": "赤峰市", "341700": "池州市", "469023": "澄迈县", "130800": "承德市", "510100": "成都市", "431000": "郴州市", "445100": "潮州市", "211300": "朝阳市", "320400": "常州市", "430700": "常德市", "469026": "昌江黎族自治县", "652300": "昌吉回族自治州", "540300": "昌都市", "130900": "沧州市", "652700": "博尔塔拉蒙古自治州", "341600": "亳州市", "371600": "滨州市", "520500": "毕节市", "210500": "本溪市", "659005": "北屯市", "110100": "北京市", "450500": "北海市", "469029": "保亭黎族苗族自治县", "530500": "保山市", "130600": "保定市", "610300": "宝鸡市", "150200": "包头市", "340300": "蚌埠市", "451000": "百色市", "620400": "白银市", "220600": "白山市", "469025": "白沙黎族自治县", "220800": "白城市", "511900": "巴中市", "652800": "巴音郭楞蒙古自治州", "150800": "巴彦淖尔市", "820000": "澳门", "210300": "鞍山市", "410500": "安阳市", "520400": "安顺市", "340800": "安庆市", "610900": "安康市", "542500": "阿里地区", "654300": "阿勒泰地区", "152900": "阿拉善盟", "659002": "阿拉尔市", "652900": "阿克苏地区", "513200": "阿坝藏族羌族自治州", } The provided code snippet includes necessary dependencies for implementing the `migration_scale_baidu` function. Write a Python function `def migration_scale_baidu(area="武汉市", indicator="move_out", date="20210112")` to solve the following problem: 百度地图慧眼-百度迁徙-迁徙规模 * 迁徙规模指数:反映迁入或迁出人口规模,城市间可横向对比 * 城市迁徙边界采用该城市行政区划,包含该城市管辖的区、县、乡、村 https://qianxi.baidu.com/?from=shoubai#city=0 :param area: 可以输入 省份 或者 具体城市 但是需要用全称 :type area: str :param indicator: move_in 迁入 move_out 迁出 :type indicator: str :param date: 结束查询的日期 20200101 以后的时间 :type end_date: str :return: 时间序列的迁徙规模指数 :rtype: pandas.DataFrame Here is the function: def migration_scale_baidu(area="武汉市", indicator="move_out", date="20210112"): """ 百度地图慧眼-百度迁徙-迁徙规模 * 迁徙规模指数:反映迁入或迁出人口规模,城市间可横向对比 * 城市迁徙边界采用该城市行政区划,包含该城市管辖的区、县、乡、村 https://qianxi.baidu.com/?from=shoubai#city=0 :param area: 可以输入 省份 或者 具体城市 但是需要用全称 :type area: str :param indicator: move_in 迁入 move_out 迁出 :type indicator: str :param date: 结束查询的日期 20200101 以后的时间 :type end_date: str :return: 时间序列的迁徙规模指数 :rtype: pandas.DataFrame """ try: if area == "全国": payload = { "dt": "country", "id": 0, "type": indicator, "date": date } else: city_dict.update(province_dict) inner_dict = dict(zip(city_dict.values(), city_dict.keys())) try: if inner_dict[area] in province_dict.keys(): dt_flag = "province" else: dt_flag = "city" payload = { "dt": dt_flag, "id": inner_dict[area], "type": indicator, "date": date } except Exception as e: return "省份 或者 具体城市名 错误" url = "https://huiyan.baidu.com/migration/historycurve.jsonp" r = requests.get(url, params=payload) json_data = json.loads(r.text[r.text.find("({") + 1 : r.text.rfind(");")]) temp_df = pd.DataFrame.from_dict(json_data["data"]["list"], orient="index") temp_df.index = pd.to_datetime(temp_df.index) temp_df.columns = ["迁徙规模指数"] return temp_df except: return None
百度地图慧眼-百度迁徙-迁徙规模 * 迁徙规模指数:反映迁入或迁出人口规模,城市间可横向对比 * 城市迁徙边界采用该城市行政区划,包含该城市管辖的区、县、乡、村 https://qianxi.baidu.com/?from=shoubai#city=0 :param area: 可以输入 省份 或者 具体城市 但是需要用全称 :type area: str :param indicator: move_in 迁入 move_out 迁出 :type indicator: str :param date: 结束查询的日期 20200101 以后的时间 :type end_date: str :return: 时间序列的迁徙规模指数 :rtype: pandas.DataFrame
160,419
import pandas as pd import requests The provided code snippet includes necessary dependencies for implementing the `history_daily` function. Write a Python function `def history_daily()` to solve the following problem: 历史上的今日 Returns ------- DataFrame "year,title, type, link, desc"" Here is the function: def history_daily(): """ 历史上的今日 Returns ------- DataFrame "year,title, type, link, desc"" """ try: url = "https://www.bjsoubang.com/api/getHistoryDaily" r = requests.get(url=url) res_list = json.loads(r.text)['info'] df = pd.DataFrame(res_list) df = df.drop(['cover', 'festival', 'recommend'], axis=1) return df except: return None
历史上的今日 Returns ------- DataFrame "year,title, type, link, desc""
160,420
import time import demjson import jsonpath import requests import pandas as pd from io import BytesIO from PIL import Image from bs4 import BeautifulSoup The provided code snippet includes necessary dependencies for implementing the `covid_163` function. Write a Python function `def covid_163(indicator="实时")` to solve the following problem: 网易-新冠状病毒 https://news.163.com/special/epidemic/?spssid=93326430940df93a37229666dfbc4b96&spsw=4&spss=other&#map_block https://news.163.com/special/epidemic/?spssid=93326430940df93a37229666dfbc4b96&spsw=4&spss=other& :return: 返回指定 indicator 的数据 :rtype: pandas.DataFrame Here is the function: def covid_163(indicator="实时"): """ 网易-新冠状病毒 https://news.163.com/special/epidemic/?spssid=93326430940df93a37229666dfbc4b96&spsw=4&spss=other&#map_block https://news.163.com/special/epidemic/?spssid=93326430940df93a37229666dfbc4b96&spsw=4&spss=other& :return: 返回指定 indicator 的数据 :rtype: pandas.DataFrame """ url = "https://c.m.163.com/ug/api/wuhan/app/data/list-total" headers = { "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36", } payload = { "t": int(time.time() * 1000), } r = requests.get(url, params=payload, headers=headers) data_json = r.json() # data info url = "https://news.163.com/special/epidemic/" r = requests.get(url, headers=headers) soup = BeautifulSoup(r.text, "lxml") data_info_df = pd.DataFrame( [ item.text.strip().split(".")[1] for item in soup.find("div", attrs={"class": "data_tip_pop_text"}).find_all( "p" ) ] ) data_info_df.columns = ["info"] # 中国历史时点数据 hist_today_df = pd.DataFrame( [item["today"] for item in data_json["data"]["chinaDayList"]], index=[item["date"] for item in data_json["data"]["chinaDayList"]], ) # 中国历史累计数据 hist_total_df = pd.DataFrame( [item["total"] for item in data_json["data"]["chinaDayList"]], index=[item["date"] for item in data_json["data"]["chinaDayList"]], ) # 中国实时数据 current_df = pd.DataFrame.from_dict(data_json["data"]["chinaTotal"]) # 世界历史时点数据 outside_today_df = pd.DataFrame( [item["today"] for item in data_json["data"]["areaTree"]], index=[item["name"] for item in data_json["data"]["areaTree"]], ) # 世界历史累计数据 outside_total_df = pd.DataFrame( [item["total"] for item in data_json["data"]["areaTree"]], index=[item["name"] for item in data_json["data"]["areaTree"]], ) # 全球所有国家及地区时点数据 all_world_today_df = pd.DataFrame( jsonpath.jsonpath(data_json["data"]["areaTree"], "$..today"), index=jsonpath.jsonpath(data_json["data"]["areaTree"], "$..name"), ) # 全球所有国家及地区累计数据 all_world_total_df = pd.DataFrame( jsonpath.jsonpath(data_json["data"]["areaTree"], "$..total"), index=jsonpath.jsonpath(data_json["data"]["areaTree"], "$..name"), ) # 中国各地区时点数据 area_total_df = pd.DataFrame( [item["total"] for item in data_json["data"]["areaTree"][0]["children"]], index=[item["name"] for item in data_json["data"]["areaTree"][0]["children"]], ) # 中国各地区累计数据 area_today_df = pd.DataFrame( [item["today"] for item in data_json["data"]["areaTree"][0]["children"]], index=[item["name"] for item in data_json["data"]["areaTree"][0]["children"]], ) # 疫情学术进展 url_article = "https://vip.open.163.com/api/cms/topic/list" payload_article = { "topicid": "00019NGQ", "listnum": "1000", "liststart": "0", "pointstart": "0", "pointend": "255", "useproperty": "true", } r_article = requests.get(url_article, params=payload_article) article_df = pd.DataFrame(r_article.json()["data"]).iloc[:, 1:] # 咨询 url_info = "https://ent.163.com/special/00035080/virus_report_data.js" payload_info = { "_": int(time.time() * 1000), "callback": "callback", } r_info = requests.get(url_info, params=payload_info, headers=headers) data_info_text = r_info.text data_info_json = demjson.decode(data_info_text.strip(" callback(")[:-1]) if indicator == "数据说明": print(f"数据更新时间: {data_json['data']['lastUpdateTime']}") return data_info_df if indicator == "中国实时数据": print(f"数据更新时间: {data_json['data']['lastUpdateTime']}") return current_df if indicator == "中国历史时点数据": print(f"数据更新时间: {data_json['data']['lastUpdateTime']}") return hist_today_df if indicator == "中国历史累计数据": print(f"数据更新时间: {data_json['data']['lastUpdateTime']}") return hist_total_df if indicator == "世界历史时点数据": print(f"数据更新时间: {data_json['data']['lastUpdateTime']}") return outside_today_df if indicator == "世界历史累计数据": print(f"数据更新时间: {data_json['data']['lastUpdateTime']}") return outside_total_df if indicator == "全球所有国家及地区时点数据": print(f"数据更新时间: {data_json['data']['lastUpdateTime']}") return all_world_today_df elif indicator == "全球所有国家及地区累计数据": print(f"数据更新时间: {data_json['data']['lastUpdateTime']}") return all_world_total_df elif indicator == "中国各地区时点数据": print(f"数据更新时间: {data_json['data']['lastUpdateTime']}") return area_today_df elif indicator == "中国各地区累计数据": print(f"数据更新时间: {data_json['data']['lastUpdateTime']}") return area_total_df elif indicator == "疫情学术进展": return article_df elif indicator == "实时资讯新闻播报": return pd.DataFrame(data_info_json["list"]) elif indicator == "实时医院新闻播报": return pd.DataFrame(data_info_json["hospital"]) elif indicator == "前沿知识": return pd.DataFrame(data_info_json["papers"]) elif indicator == "权威发布": return pd.DataFrame(data_info_json["power"]) elif indicator == "滚动新闻": return pd.DataFrame(data_info_json["scrollNews"])
网易-新冠状病毒 https://news.163.com/special/epidemic/?spssid=93326430940df93a37229666dfbc4b96&spsw=4&spss=other&#map_block https://news.163.com/special/epidemic/?spssid=93326430940df93a37229666dfbc4b96&spsw=4&spss=other& :return: 返回指定 indicator 的数据 :rtype: pandas.DataFrame
160,421
import time import demjson import jsonpath import requests import pandas as pd from io import BytesIO from PIL import Image from bs4 import BeautifulSoup The provided code snippet includes necessary dependencies for implementing the `covid_dxy` function. Write a Python function `def covid_dxy(indicator="湖北")` to solve the following problem: 20200315-丁香园接口更新分为国内和国外 丁香园-全国统计-info 丁香园-分地区统计-data 丁香园-全国发热门诊一览表-hospital 丁香园-全国新闻-news :param indicator: ["info", "data", "hospital", "news"] :type indicator: str :return: 返回指定 indicator 的数据 :rtype: pandas.DataFrame Here is the function: def covid_dxy(indicator="湖北"): """ 20200315-丁香园接口更新分为国内和国外 丁香园-全国统计-info 丁香园-分地区统计-data 丁香园-全国发热门诊一览表-hospital 丁香园-全国新闻-news :param indicator: ["info", "data", "hospital", "news"] :type indicator: str :return: 返回指定 indicator 的数据 :rtype: pandas.DataFrame """ url = "https://3g.dxy.cn/newh5/view/pneumonia" r = requests.get(url) r.encoding = "utf-8" soup = BeautifulSoup(r.text, "lxml") # news-china text_data_news = str( soup.find_all("script", attrs={"id": "getTimelineServiceundefined"}) ) temp_json = text_data_news[ text_data_news.find("= [{") + 2 : text_data_news.rfind("}catch") ] if temp_json: json_data = pd.DataFrame(json.loads(temp_json)) chinese_news = json_data[ ["title", "summary", "infoSource", "provinceName", "sourceUrl"] ] # news-foreign text_data_news = str(soup.find_all("script", attrs={"id": "getTimelineService2"})) temp_json = text_data_news[ text_data_news.find("= [{") + 2 : text_data_news.rfind("}catch") ] json_data = pd.DataFrame(json.loads(temp_json)) foreign_news = json_data # data-domestic data_text = str(soup.find("script", attrs={"id": "getAreaStat"})) data_text_json = json.loads( data_text[data_text.find("= [{") + 2 : data_text.rfind("catch") - 1] ) big_df = pd.DataFrame() for i, p in enumerate(jsonpath.jsonpath(data_text_json, "$..provinceName")): temp_df = pd.DataFrame(jsonpath.jsonpath(data_text_json, "$..cities")[i]) temp_df["province"] = p big_df = big_df.append(temp_df, ignore_index=True) domestic_city_df = big_df data_df = pd.DataFrame(data_text_json).iloc[:, :7] data_df.columns = ["地区", "地区简称", "现存确诊", "累计确诊", "-", "治愈", "死亡"] domestic_province_df = data_df[["地区", "地区简称", "现存确诊", "累计确诊", "治愈", "死亡"]] # data-global data_text = str( soup.find("script", attrs={"id": "getListByCountryTypeService2true"}) ) data_text_json = json.loads( data_text[data_text.find("= [{") + 2: data_text.rfind("catch") - 1] ) global_df = pd.DataFrame(data_text_json) # info dxy_static = soup.find(attrs={"id": "getStatisticsService"}).get_text() data_json = json.loads( dxy_static[dxy_static.find("= {") + 2 : dxy_static.rfind("}c")] ) china_statistics = pd.DataFrame( [ time.strftime( "%Y-%m-%d %H:%M:%S", time.localtime(data_json["modifyTime"] / 1000) ), data_json["currentConfirmedCount"], data_json["confirmedCount"], data_json["suspectedCount"], data_json["curedCount"], data_json["deadCount"], data_json["seriousCount"], data_json["suspectedIncr"], data_json["currentConfirmedIncr"], data_json["confirmedIncr"], data_json["curedIncr"], data_json["deadIncr"], data_json["seriousIncr"], ], index=[ "数据发布时间", "现存确诊", "累计确诊", "境外输入", "累计治愈", "累计死亡", "现存重症", "境外输入较昨日", "现存确诊较昨日", "累计确诊较昨日", "累计治愈较昨日", "累计死亡较昨日", "现存重症较昨日", ], columns=["info"], ) foreign_statistics = pd.DataFrame.from_dict( data_json["foreignStatistics"], orient="index" ) global_statistics = pd.DataFrame.from_dict( data_json["globalStatistics"], orient="index" ) # hospital url = ( "https://assets.dxycdn.com/gitrepo/tod-assets/output/default/pneumonia/index.js" ) payload = {"t": str(int(time.time()))} r = requests.get(url, params=payload) hospital_df = pd.read_html(r.text)[0].iloc[:, :-1] if indicator == "中国疫情分省统计详情": return domestic_province_df if indicator == "中国疫情分市统计详情": return domestic_city_df elif indicator == "全球疫情分国家统计详情": return global_df elif indicator == "中国疫情实时统计": return china_statistics elif indicator == "国外疫情实时统计": return foreign_statistics elif indicator == "全球疫情实时统计": return global_statistics elif indicator == "中国疫情防控医院": return hospital_df elif indicator == "实时播报": return chinese_news elif indicator == "中国-新增疑似-新增确诊-趋势图": img_file = Image.open( BytesIO(requests.get(data_json["quanguoTrendChart"][0]["imgUrl"]).content) ) img_file.show() elif indicator == "中国-现存确诊-趋势图": img_file = Image.open( BytesIO(requests.get(data_json["quanguoTrendChart"][1]["imgUrl"]).content) ) img_file.show() elif indicator == "中国-现存疑似-趋势图": img_file = Image.open( BytesIO(requests.get(data_json["quanguoTrendChart"][2]["imgUrl"]).content) ) img_file.show() elif indicator == "中国-治愈-趋势图": img_file = Image.open( BytesIO(requests.get(data_json["quanguoTrendChart"][3]["imgUrl"]).content) ) img_file.show() elif indicator == "中国-死亡-趋势图": img_file = Image.open( BytesIO(requests.get(data_json["quanguoTrendChart"][4]["imgUrl"]).content) ) img_file.show() elif indicator == "中国-非湖北新增确诊-趋势图": img_file = Image.open( BytesIO(requests.get(data_json["hbFeiHbTrendChart"][0]["imgUrl"]).content) ) img_file.show() elif indicator == "中国-湖北新增确诊-趋势图": img_file = Image.open( BytesIO(requests.get(data_json["hbFeiHbTrendChart"][1]["imgUrl"]).content) ) img_file.show() elif indicator == "中国-湖北现存确诊-趋势图": img_file = Image.open( BytesIO(requests.get(data_json["hbFeiHbTrendChart"][2]["imgUrl"]).content) ) img_file.show() elif indicator == "中国-非湖北现存确诊-趋势图": img_file = Image.open( BytesIO(requests.get(data_json["hbFeiHbTrendChart"][3]["imgUrl"]).content) ) img_file.show() elif indicator == "中国-治愈-死亡-趋势图": img_file = Image.open( BytesIO(requests.get(data_json["hbFeiHbTrendChart"][4]["imgUrl"]).content) ) img_file.show() elif indicator == "国外-国外新增确诊-趋势图": img_file = Image.open( BytesIO(requests.get(data_json["foreignTrendChart"][0]["imgUrl"]).content) ) img_file.show() elif indicator == "国外-国外累计确诊-趋势图": img_file = Image.open( BytesIO(requests.get(data_json["foreignTrendChart"][1]["imgUrl"]).content) ) img_file.show() elif indicator == "国外-国外死亡-趋势图": img_file = Image.open( BytesIO(requests.get(data_json["foreignTrendChart"][2]["imgUrl"]).content) ) img_file.show() elif indicator == "国外-重点国家新增确诊-趋势图": img_file = Image.open( BytesIO( requests.get( data_json["importantForeignTrendChart"][0]["imgUrl"] ).content ) ) img_file.show() elif indicator == "国外-日本新增确诊-趋势图": img_file = Image.open( BytesIO( requests.get( data_json["importantForeignTrendChart"][1]["imgUrl"] ).content ) ) img_file.show() elif indicator == "国外-意大利新增确诊-趋势图": img_file = Image.open( BytesIO( requests.get( data_json["importantForeignTrendChart"][2]["imgUrl"] ).content ) ) img_file.show() elif indicator == "国外-伊朗新增确诊-趋势图": img_file = Image.open( BytesIO( requests.get( data_json["importantForeignTrendChart"][3]["imgUrl"] ).content ) ) img_file.show() elif indicator == "国外-美国新增确诊-趋势图": img_file = Image.open( BytesIO( requests.get( data_json["importantForeignTrendChart"][4]["imgUrl"] ).content ) ) img_file.show() elif indicator == "国外-法国新增确诊-趋势图": img_file = Image.open( BytesIO( requests.get( data_json["importantForeignTrendChart"][5]["imgUrl"] ).content ) ) img_file.show() elif indicator == "国外-德国新增确诊-趋势图": img_file = Image.open( BytesIO( requests.get( data_json["importantForeignTrendChart"][6]["imgUrl"] ).content ) ) img_file.show() elif indicator == "国外-西班牙新增确诊-趋势图": img_file = Image.open( BytesIO( requests.get( data_json["importantForeignTrendChart"][7]["imgUrl"] ).content ) ) img_file.show() elif indicator == "国外-韩国新增确诊-趋势图": img_file = Image.open( BytesIO( requests.get( data_json["importantForeignTrendChart"][8]["imgUrl"] ).content ) ) img_file.show() else: try: data_text = str(soup.find("script", attrs={"id": "getAreaStat"})) data_text_json = json.loads( data_text[data_text.find("= [{") + 2 : data_text.rfind("catch") - 1] ) data_df = pd.DataFrame(data_text_json) sub_area = pd.DataFrame( data_df[data_df["provinceName"] == indicator]["cities"].values[0] ) if sub_area.empty: return print("暂无分区域数据") sub_area.columns = ["区域", "现在确诊人数", "确诊人数", "疑似人数", "治愈人数", "死亡人数", "id"] sub_area = sub_area[["区域", "现在确诊人数", "确诊人数", "疑似人数", "治愈人数", "死亡人数"]] return sub_area except IndexError as e: print("请输入省/市的全称, 如: 浙江省/上海市 等")
20200315-丁香园接口更新分为国内和国外 丁香园-全国统计-info 丁香园-分地区统计-data 丁香园-全国发热门诊一览表-hospital 丁香园-全国新闻-news :param indicator: ["info", "data", "hospital", "news"] :type indicator: str :return: 返回指定 indicator 的数据 :rtype: pandas.DataFrame
160,422
import time import demjson import jsonpath import requests import pandas as pd from io import BytesIO from PIL import Image from bs4 import BeautifulSoup The provided code snippet includes necessary dependencies for implementing the `covid_baidu` function. Write a Python function `def covid_baidu(indicator="湖北")` to solve the following problem: 百度-新型冠状病毒肺炎-疫情实时大数据报告 https://voice.baidu.com/act/newpneumonia/newpneumonia/?from=osari_pc_1 :param indicator: 看说明文档 :type indicator: str :return: 指定 indicator 的数据 :rtype: pandas.DataFrame Here is the function: def covid_baidu(indicator="湖北"): """ 百度-新型冠状病毒肺炎-疫情实时大数据报告 https://voice.baidu.com/act/newpneumonia/newpneumonia/?from=osari_pc_1 :param indicator: 看说明文档 :type indicator: str :return: 指定 indicator 的数据 :rtype: pandas.DataFrame """ url = "https://huiyan.baidu.com/openapi/v1/migration/rank" payload = { "type": "move", "ak": "kgD2HiDnLdUhwzd3CLuG5AWNfX3fhLYe", "adminType": "country", "name": "全国", } r = requests.get(url, params=payload) move_in_df = pd.DataFrame(r.json()["result"]["moveInList"]) move_out_df = pd.DataFrame(r.json()["result"]["moveOutList"]) url = "https://opendata.baidu.com/api.php" payload = { "query": "全国", "resource_id": "39258", "tn": "wisetpl", "format": "json", "cb": "jsonp_1580470773343_11183", } r = requests.get(url, params=payload) text_data = r.text json_data_news = json.loads( text_data.strip("/**/jsonp_1580470773343_11183(").rstrip(");") ) url = "https://opendata.baidu.com/data/inner" payload = { "tn": "reserved_all_res_tn", "dspName": "iphone", "from_sf": "1", "dsp": "iphone", "resource_id": "28565", "alr": "1", "query": "肺炎", "cb": "jsonp_1606895491198_93137", } r = requests.get(url, params=payload) json_data = json.loads(r.text[r.text.find("({") + 1 : r.text.rfind(");")]) spot_report = pd.DataFrame(json_data["Result"][0]["DisplayData"]["result"]["items"]) # domestic-city url = "https://voice.baidu.com/act/newpneumonia/newpneumonia/?from=osari_pc_1" r = requests.get(url) soup = BeautifulSoup(r.text, "lxml") data_json = demjson.decode(soup.find(attrs={"id": "captain-config"}).text) big_df = pd.DataFrame() for i, p in enumerate( jsonpath.jsonpath(data_json["component"][0]["caseList"], "$..area") ): temp_df = pd.DataFrame( jsonpath.jsonpath(data_json["component"][0]["caseList"], "$..subList")[i] ) temp_df["province"] = p big_df = big_df.append(temp_df, ignore_index=True) domestic_city_df = big_df domestic_province_df = pd.DataFrame(data_json["component"][0]["caseList"]).iloc[ :, :-2 ] big_df = pd.DataFrame() for i, p in enumerate( jsonpath.jsonpath(data_json["component"][0]["caseOutsideList"], "$..area") ): temp_df = pd.DataFrame( jsonpath.jsonpath( data_json["component"][0]["caseOutsideList"], "$..subList" )[i] ) temp_df["province"] = p big_df = big_df.append(temp_df, ignore_index=True) outside_city_df = big_df outside_country_df = pd.DataFrame( data_json["component"][0]["caseOutsideList"] ).iloc[:, :-1] big_df = pd.DataFrame() for i, p in enumerate( jsonpath.jsonpath(data_json["component"][0]["globalList"], "$..area") ): temp_df = pd.DataFrame( jsonpath.jsonpath(data_json["component"][0]["globalList"], "$..subList")[i] ) temp_df["province"] = p big_df = big_df.append(temp_df, ignore_index=True) global_country_df = big_df global_continent_df = pd.DataFrame(data_json["component"][0]["globalList"])[ ["area", "died", "crued", "confirmed", "confirmedRelative"] ] if indicator == "热门迁入地": return move_in_df elif indicator == "热门迁出地": return move_out_df elif indicator == "今日疫情热搜": return pd.DataFrame(json_data_news["data"][0]["list"][0]["item"]) elif indicator == "防疫知识热搜": return pd.DataFrame(json_data_news["data"][0]["list"][1]["item"]) elif indicator == "热搜谣言粉碎": return pd.DataFrame(json_data_news["data"][0]["list"][2]["item"]) elif indicator == "复工复课热搜": return pd.DataFrame(json_data_news["data"][0]["list"][3]["item"]) elif indicator == "热门人物榜": return pd.DataFrame(json_data_news["data"][0]["list"][4]["item"]) elif indicator == "历史疫情热搜": return pd.DataFrame(json_data_news["data"][0]["list"][5]["item"]) elif indicator == "搜索正能量榜": return pd.DataFrame(json_data_news["data"][0]["list"][6]["item"]) elif indicator == "游戏榜": return pd.DataFrame(json_data_news["data"][0]["list"][7]["item"]) elif indicator == "影视榜": return pd.DataFrame(json_data_news["data"][0]["list"][8]["item"]) elif indicator == "小说榜": return pd.DataFrame(json_data_news["data"][0]["list"][9]["item"]) elif indicator == "疫期飙升榜": return pd.DataFrame(json_data_news["data"][0]["list"][10]["item"]) elif indicator == "实时播报": return spot_report elif indicator == "中国分省份详情": return domestic_province_df elif indicator == "中国分城市详情": return domestic_city_df elif indicator == "国外分国详情": return outside_country_df elif indicator == "国外分城市详情": return outside_city_df elif indicator == "全球分洲详情": return global_continent_df elif indicator == "全球分洲国家详情": return global_country_df
百度-新型冠状病毒肺炎-疫情实时大数据报告 https://voice.baidu.com/act/newpneumonia/newpneumonia/?from=osari_pc_1 :param indicator: 看说明文档 :type indicator: str :return: 指定 indicator 的数据 :rtype: pandas.DataFrame
160,423
import time import demjson import jsonpath import requests import pandas as pd from io import BytesIO from PIL import Image from bs4 import BeautifulSoup The provided code snippet includes necessary dependencies for implementing the `covid_hist_city` function. Write a Python function `def covid_hist_city(city="武汉市")` to solve the following problem: 疫情历史数据 城市 https://github.com/canghailan/Wuhan-2019-nCoV 2019-12-01开始 :return: 具体城市的疫情数据 :rtype: pandas.DataFrame Here is the function: def covid_hist_city(city="武汉市"): """ 疫情历史数据 城市 https://github.com/canghailan/Wuhan-2019-nCoV 2019-12-01开始 :return: 具体城市的疫情数据 :rtype: pandas.DataFrame """ url = "https://raw.githubusercontent.com/canghailan/Wuhan-2019-nCoV/master/Wuhan-2019-nCoV.json" r = requests.get(url) data_json = r.json() data_df = pd.DataFrame(data_json) return data_df[data_df["city"] == city]
疫情历史数据 城市 https://github.com/canghailan/Wuhan-2019-nCoV 2019-12-01开始 :return: 具体城市的疫情数据 :rtype: pandas.DataFrame
160,424
import time import demjson import jsonpath import requests import pandas as pd from io import BytesIO from PIL import Image from bs4 import BeautifulSoup The provided code snippet includes necessary dependencies for implementing the `covid_hist_province` function. Write a Python function `def covid_hist_province(province="湖北省")` to solve the following problem: 疫情历史数据 省份 https://github.com/canghailan/Wuhan-2019-nCoV 2019-12-01开始 :return: 具体省份的疫情数据 :rtype: pandas.DataFrame Here is the function: def covid_hist_province(province="湖北省"): """ 疫情历史数据 省份 https://github.com/canghailan/Wuhan-2019-nCoV 2019-12-01开始 :return: 具体省份的疫情数据 :rtype: pandas.DataFrame """ url = "https://raw.githubusercontent.com/canghailan/Wuhan-2019-nCoV/master/Wuhan-2019-nCoV.json" r = requests.get(url) data_json = r.json() data_df = pd.DataFrame(data_json) return data_df[data_df["province"] == province]
疫情历史数据 省份 https://github.com/canghailan/Wuhan-2019-nCoV 2019-12-01开始 :return: 具体省份的疫情数据 :rtype: pandas.DataFrame
160,425
import os import pandas as pd import requests import execjs from gopup.movie.cons import headers from gopup.utils.date_utils import today, day_last_date def get_js(js_url): js_url = "http://www.gopup.cn/static/lib/webDES.js" r = requests.get(url=js_url) return r.text "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36", } def today(): """ 获取当天日期 年-月-日 """ day = datetime.datetime.today().date() return str(day) The provided code snippet includes necessary dependencies for implementing the `realtime_boxoffice` function. Write a Python function `def realtime_boxoffice()` to solve the following problem: 获取实时电影票房数据 数据来源:EBOT艺恩票房智库 https://www.endata.com.cn/BoxOffice :return: DataFrame BoxOffice 实时票房(万) Irank 排名 MovieName 影片名 boxPer 票房占比 (%) movieDay 上映天数 sumBoxOffice 累计票房(万) default_url 影片海报 Here is the function: def realtime_boxoffice(): """ 获取实时电影票房数据 数据来源:EBOT艺恩票房智库 https://www.endata.com.cn/BoxOffice :return: DataFrame BoxOffice 实时票房(万) Irank 排名 MovieName 影片名 boxPer 票房占比 (%) movieDay 上映天数 sumBoxOffice 累计票房(万) default_url 影片海报 """ try: url = "https://www.endata.com.cn/API/GetData.ashx" data = { "tdate": today(), "MethodName": "BoxOffice_GetHourBoxOffice" } r = requests.post(url=url, data=data, headers=headers) js = get_js('webDES.js') docjs = execjs.compile(js) res = docjs.call("webInstace.shell", r.text) res_dict = json.loads(res) if res_dict['Status'] == 1: tmp = res_dict['Data']['Table1'] res_pd = pd.DataFrame(tmp) res_pd = res_pd.drop(columns=['moblie_url', 'larger_url', 'mId', 'MovieImg']) return res_pd except Exception as e: return None
获取实时电影票房数据 数据来源:EBOT艺恩票房智库 https://www.endata.com.cn/BoxOffice :return: DataFrame BoxOffice 实时票房(万) Irank 排名 MovieName 影片名 boxPer 票房占比 (%) movieDay 上映天数 sumBoxOffice 累计票房(万) default_url 影片海报
160,426
import os import pandas as pd import requests import execjs from gopup.movie.cons import headers from gopup.utils.date_utils import today, day_last_date def get_js(js_url): js_url = "http://www.gopup.cn/static/lib/webDES.js" r = requests.get(url=js_url) return r.text "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36", } def today(): """ 获取当天日期 年-月-日 """ day = datetime.datetime.today().date() return str(day) def day_last_date(date, days=-1): """ 获得某天的之前一天日期 :param date: 日期 """ dd = datetime.datetime.strptime(date, "%Y-%m-%d") lasty = dd + datetime.timedelta(days) return str(lasty)[0:10] The provided code snippet includes necessary dependencies for implementing the `day_boxoffice` function. Write a Python function `def day_boxoffice(date=None)` to solve the following problem: 获取单日电影票房数据 数据来源:EBOT艺恩票房智库 https://www.endata.com.cn/BoxOffice :param date: 日期 :return: DataFrame Irank 排名 MovieName 影片名 BoxOffice 单日票房(万) BoxOffice_Up 环比变化 SumBoxOffice 累计票房(万) default_url 影片海报 AvgPrice 平均票价 AvpPeoPle 场均人次 RapIndex 口碑指数 MovieDay 上映天数 Here is the function: def day_boxoffice(date=None): """ 获取单日电影票房数据 数据来源:EBOT艺恩票房智库 https://www.endata.com.cn/BoxOffice :param date: 日期 :return: DataFrame Irank 排名 MovieName 影片名 BoxOffice 单日票房(万) BoxOffice_Up 环比变化 SumBoxOffice 累计票房(万) default_url 影片海报 AvgPrice 平均票价 AvpPeoPle 场均人次 RapIndex 口碑指数 MovieDay 上映天数 """ try: if date == None: edate = today() else: edate = date sdate = day_last_date(edate, days=1) url = "https://www.endata.com.cn/API/GetData.ashx" data = { "sdate": sdate, "edate": edate, "MethodName": "BoxOffice_GetDayBoxOffice" } r = requests.post(url=url, data=data, headers=headers) js = get_js('webDES.js') docjs = execjs.compile(js) res = docjs.call("webInstace.shell", r.text) res_dict = json.loads(res) if res_dict['Status'] == 1: tmp = res_dict['Data']['Table'] res_pd = pd.DataFrame(tmp) res_pd = res_pd.drop(columns=['MovieImg', 'moblie_url', 'larger_url', 'MovieID', 'Director', 'BoxOffice1', 'IRank_pro', 'RapIndex']) return res_pd except Exception as e: return None
获取单日电影票房数据 数据来源:EBOT艺恩票房智库 https://www.endata.com.cn/BoxOffice :param date: 日期 :return: DataFrame Irank 排名 MovieName 影片名 BoxOffice 单日票房(万) BoxOffice_Up 环比变化 SumBoxOffice 累计票房(万) default_url 影片海报 AvgPrice 平均票价 AvpPeoPle 场均人次 RapIndex 口碑指数 MovieDay 上映天数
160,427
import os import pandas as pd import requests import execjs from gopup.movie.cons import headers from gopup.utils.date_utils import today, day_last_date def get_js(js_url): js_url = "http://www.gopup.cn/static/lib/webDES.js" r = requests.get(url=js_url) return r.text "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36", } The provided code snippet includes necessary dependencies for implementing the `day_cinema` function. Write a Python function `def day_cinema(date=None)` to solve the following problem: 获取单日影院票房 :param date: :return: DataFrame RowNum 排名 CinemaName 影院名称 TodayBox 单日票房(元) TodayShowCount 单日场次 AvgPeople 场均人次 price 场均票价(元) Attendance 上座率 Here is the function: def day_cinema(date=None): """ 获取单日影院票房 :param date: :return: DataFrame RowNum 排名 CinemaName 影院名称 TodayBox 单日票房(元) TodayShowCount 单日场次 AvgPeople 场均人次 price 场均票价(元) Attendance 上座率 """ try: url = "https://www.endata.com.cn/API/GetData.ashx" data = { "date": date, "rowNum1": 1, "rowNum2": 100, "MethodName": "BoxOffice_GetCinemaDayBoxOffice" } r = requests.post(url=url, data=data, headers=headers) js = get_js('webDES.js') docjs = execjs.compile(js) res = docjs.call("webInstace.shell", r.text) res_dict = json.loads(res) if res_dict['Status'] == 1: tmp = res_dict['Data']['Table'] res_pd = pd.DataFrame(tmp) res_pd = res_pd.drop( columns=['CinemaID', 'TodayAudienceCount', 'TodayOfferSeat']) return res_pd except Exception as e: return None
获取单日影院票房 :param date: :return: DataFrame RowNum 排名 CinemaName 影院名称 TodayBox 单日票房(元) TodayShowCount 单日场次 AvgPeople 场均人次 price 场均票价(元) Attendance 上座率
160,428
import os import pandas as pd import requests import execjs from gopup.movie.cons import headers from gopup.utils.date_utils import today, day_last_date def get_js(js_url): js_url = "http://www.gopup.cn/static/lib/webDES.js" r = requests.get(url=js_url) return r.text "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36", } The provided code snippet includes necessary dependencies for implementing the `realtime_tv` function. Write a Python function `def realtime_tv()` to solve the following problem: 获取实时电视剧播映指数 数据来源:EBOT艺恩票房智库 https://www.endata.com.cn/BoxOffice/Video/index.html :return: DataFrame TvName 名称 Irank 排名 Genres 类型 PlayIndex 播映指数 MediaHot 媒体热度 UserHot 用户热度 AnswerHot 好评度 PlayHot 观看度 date 日期 Here is the function: def realtime_tv(): """ 获取实时电视剧播映指数 数据来源:EBOT艺恩票房智库 https://www.endata.com.cn/BoxOffice/Video/index.html :return: DataFrame TvName 名称 Irank 排名 Genres 类型 PlayIndex 播映指数 MediaHot 媒体热度 UserHot 用户热度 AnswerHot 好评度 PlayHot 观看度 date 日期 """ try: url = "https://www.endata.com.cn/API/GetData.ashx" data = { "tvType": 2, "MethodName": "BoxOffice_GetTvData_PlayIndexRank" } r = requests.post(url=url, data=data, headers=headers) js = get_js('webDES.js') docjs = execjs.compile(js) res = docjs.call("webInstace.shell", r.text) res_dict = json.loads(res) if res_dict['Status'] == 1: tmp = res_dict['Data']['Table'] res_pd = pd.DataFrame(tmp) res_pd['date'] = res_dict['Data']['Table1'][0]['MaxDate'] return res_pd except Exception as e: return None
获取实时电视剧播映指数 数据来源:EBOT艺恩票房智库 https://www.endata.com.cn/BoxOffice/Video/index.html :return: DataFrame TvName 名称 Irank 排名 Genres 类型 PlayIndex 播映指数 MediaHot 媒体热度 UserHot 用户热度 AnswerHot 好评度 PlayHot 观看度 date 日期
160,429
import os import pandas as pd import requests import execjs from gopup.movie.cons import headers from gopup.utils.date_utils import today, day_last_date def get_js(js_url): js_url = "http://www.gopup.cn/static/lib/webDES.js" r = requests.get(url=js_url) return r.text "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36", } The provided code snippet includes necessary dependencies for implementing the `realtime_show` function. Write a Python function `def realtime_show()` to solve the following problem: 获取实时综艺播映指数 数据来源:EBOT艺恩票房智库 https://www.endata.com.cn/BoxOffice/Video/index.html :return: DataFrame TvName 名称 Irank 排名 Genres 类型 PlayIndex 播映指数 MediaHot 媒体热度 UserHot 用户热度 AnswerHot 好评度 PlayHot 观看度 date 日期 Here is the function: def realtime_show(): """ 获取实时综艺播映指数 数据来源:EBOT艺恩票房智库 https://www.endata.com.cn/BoxOffice/Video/index.html :return: DataFrame TvName 名称 Irank 排名 Genres 类型 PlayIndex 播映指数 MediaHot 媒体热度 UserHot 用户热度 AnswerHot 好评度 PlayHot 观看度 date 日期 """ try: url = "https://www.endata.com.cn/API/GetData.ashx" data = { "tvType": 8, "MethodName": "BoxOffice_GetTvData_PlayIndexRank" } r = requests.post(url=url, data=data, headers=headers) js = get_js('webDES.js') docjs = execjs.compile(js) res = docjs.call("webInstace.shell", r.text) res_dict = json.loads(res) if res_dict['Status'] == 1: tmp = res_dict['Data']['Table'] res_pd = pd.DataFrame(tmp) res_pd['date'] = res_dict['Data']['Table1'][0]['MaxDate'] return res_pd except Exception as e: return None
获取实时综艺播映指数 数据来源:EBOT艺恩票房智库 https://www.endata.com.cn/BoxOffice/Video/index.html :return: DataFrame TvName 名称 Irank 排名 Genres 类型 PlayIndex 播映指数 MediaHot 媒体热度 UserHot 用户热度 AnswerHot 好评度 PlayHot 观看度 date 日期
160,430
import os import pandas as pd import requests import execjs from gopup.movie.cons import headers from gopup.utils.date_utils import today, day_last_date def get_js(js_url): js_url = "http://www.gopup.cn/static/lib/webDES.js" r = requests.get(url=js_url) return r.text "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36", } The provided code snippet includes necessary dependencies for implementing the `realtime_artist` function. Write a Python function `def realtime_artist()` to solve the following problem: 获取艺人商业价值 数据来源:EBOT艺恩票房智库 https://www.endata.com.cn/BoxOffice/Marketing/Artist/business.html :return: DataFrame StarBaseName 艺人 Irank 排名 BusinessValueIndex_L1 商业价值 MajorHotIndex_L2 专业热度 FocusHotIndex_L2 关注热度 PredictHotIndex_L2 预测热度 ReputationIndex_L3 美誉度 Here is the function: def realtime_artist(): """ 获取艺人商业价值 数据来源:EBOT艺恩票房智库 https://www.endata.com.cn/BoxOffice/Marketing/Artist/business.html :return: DataFrame StarBaseName 艺人 Irank 排名 BusinessValueIndex_L1 商业价值 MajorHotIndex_L2 专业热度 FocusHotIndex_L2 关注热度 PredictHotIndex_L2 预测热度 ReputationIndex_L3 美誉度 """ try: url = "https://www.endata.com.cn/API/GetData.ashx" data = { "Order": "BusinessValueIndex_L1", "OrderType": "DESC", "PageIndex": 1, "PageSize": 100, "MethodName": "Data_GetList_Star" } r = requests.post(url=url, data=data, headers=headers) js = get_js('webDES.js') docjs = execjs.compile(js) res = docjs.call("webInstace.shell", r.text) res_dict = json.loads(res) if res_dict['Status'] == 1: tmp = res_dict['Data']['Table'] res_pd = pd.DataFrame(tmp) res_pd = res_pd.drop( columns=['StarBaseID']) return res_pd except Exception as e: return None
获取艺人商业价值 数据来源:EBOT艺恩票房智库 https://www.endata.com.cn/BoxOffice/Marketing/Artist/business.html :return: DataFrame StarBaseName 艺人 Irank 排名 BusinessValueIndex_L1 商业价值 MajorHotIndex_L2 专业热度 FocusHotIndex_L2 关注热度 PredictHotIndex_L2 预测热度 ReputationIndex_L3 美誉度
160,431
import os import pandas as pd import requests import execjs from gopup.movie.cons import headers from gopup.utils.date_utils import today, day_last_date def get_js(js_url): js_url = "http://www.gopup.cn/static/lib/webDES.js" r = requests.get(url=js_url) return r.text "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36", } The provided code snippet includes necessary dependencies for implementing the `realtime_artist_flow` function. Write a Python function `def realtime_artist_flow()` to solve the following problem: 获取艺人流量价值 数据来源:EBOT艺恩票房智库 https://www.endata.com.cn/BoxOffice/Marketing/Artist/business.html :return: DataFrame StarBaseName 艺人 Irank 排名 FlowValueIndex_L1 流量价值 MajorHotIndex_L2 专业热度 FocusHotIndex_L2 关注热度 PredictHotIndex_L2 预测热度 TakeGoodsIndex_L2 带货力 Here is the function: def realtime_artist_flow(): """ 获取艺人流量价值 数据来源:EBOT艺恩票房智库 https://www.endata.com.cn/BoxOffice/Marketing/Artist/business.html :return: DataFrame StarBaseName 艺人 Irank 排名 FlowValueIndex_L1 流量价值 MajorHotIndex_L2 专业热度 FocusHotIndex_L2 关注热度 PredictHotIndex_L2 预测热度 TakeGoodsIndex_L2 带货力 """ try: url = "https://www.endata.com.cn/API/GetData.ashx" data = { "Order": "FlowValueIndex_L1", "OrderType": "DESC", "PageIndex": 1, "PageSize": 100, "MethodName": "Data_GetList_Star" } r = requests.post(url=url, data=data, headers=headers) js = get_js('webDES.js') docjs = execjs.compile(js) res = docjs.call("webInstace.shell", r.text) res_dict = json.loads(res) if res_dict['Status'] == 1: tmp = res_dict['Data']['Table'] res_pd = pd.DataFrame(tmp) res_pd = res_pd.drop( columns=['StarBaseID', 'ReputationIndex_L3', 'BusinessValueIndex_L1']) return res_pd except Exception as e: return None
获取艺人流量价值 数据来源:EBOT艺恩票房智库 https://www.endata.com.cn/BoxOffice/Marketing/Artist/business.html :return: DataFrame StarBaseName 艺人 Irank 排名 FlowValueIndex_L1 流量价值 MajorHotIndex_L2 专业热度 FocusHotIndex_L2 关注热度 PredictHotIndex_L2 预测热度 TakeGoodsIndex_L2 带货力
160,432
import os import pandas as pd import requests import execjs from gopup.movie.cons import headers from gopup.utils.date_utils import today, day_last_date The provided code snippet includes necessary dependencies for implementing the `_get_js_path` function. Write a Python function `def _get_js_path(name, module_file)` to solve the following problem: 获取 JS 文件的路径(从模块所在目录查找) :param name: 文件名 :param module_file: filename :return: str json_file_path Here is the function: def _get_js_path(name, module_file): """ 获取 JS 文件的路径(从模块所在目录查找) :param name: 文件名 :param module_file: filename :return: str json_file_path """ module_folder = os.path.abspath(os.path.dirname(os.path.dirname(module_file))) module_json_path = os.path.join(module_folder, "movie", name) return module_json_path
获取 JS 文件的路径(从模块所在目录查找) :param name: 文件名 :param module_file: filename :return: str json_file_path
160,433
import math import sys import requests import warnings import random from lxml import etree from time import sleep from tqdm import tqdm from collections import OrderedDict from datetime import date, datetime, timedelta import pandas as pd class Weibo(object): def __init__(self, cookie="", since_date=None, filter=1): # 初始化 cookie = cookie # 微博cookie,可填可不填 user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36' self.headers = {'User_Agent': user_agent, 'Cookie': cookie} self.query = '' # 取值范围为0、1,程序默认值为0,代表要爬取用户的全部微博,1代表只爬取用户的原创微博 self.filter = filter self.start_page = 1 # 开始爬的页,如果中途被限制而结束可以用此定义开始页码 self.user = {} # 存储目标微博用户信息 self.got_count = 0 # 存储爬取到的微博数 self.weibo = [] # 存储爬取到的所有微博信息 self.weibo_id_list = [] # 存储爬取到的所有微博id if since_date is None: dayago = (datetime.now() - timedelta(days=15)) self.since_date = dayago.strftime("%Y-%m-%d") else: self.since_date = since_date def get_json(self, params): """获取网页中json数据""" url = 'https://m.weibo.cn/api/container/getIndex?' r = requests.get(url, params=params, headers=self.headers, verify=False) return r.json() def get_weibo_json(self, page): """获取网页中微博json数据""" params = { 'container_ext': 'profile_uid:' + str(self.user_id), 'containerid': '100103type=401&q=' + self.query, 'page_type': 'searchall' } if self.query else { 'containerid': '107603' + str(self.user_id) } params['page'] = page js = self.get_json(params) return js def standardize_info(self, weibo): """标准化信息,去除乱码""" for k, v in weibo.items(): if 'bool' not in str(type(v)) and 'int' not in str( type(v)) and 'list' not in str( type(v)) and 'long' not in str(type(v)): weibo[k] = v.replace(u'\u200b', '').encode( sys.stdout.encoding, 'ignore').decode(sys.stdout.encoding) return weibo def get_user_info(self): """获取用户信息""" params = {'containerid': '100505' + str(self.user_id)} js = self.get_json(params) if js['ok']: info = js['data']['userInfo'] user_info = OrderedDict() user_info['用户id'] = self.user_id user_info['用户昵称'] = info.get('screen_name', '') gender = info.get('gender', '') user_info['性别'] = u'女' if gender == 'f' else u'男' params = { 'containerid': '230283' + str(self.user_id) + '_-_INFO' } zh_list = [ u'生日', u'所在地', u'小学', u'初中', u'高中', u'大学', u'公司', u'注册时间', u'阳光信用' ] en_list = [ 'birthday', 'location', 'education', 'education', 'education', 'education', 'company', 'registration_time', 'sunshine' ] for i in zh_list: user_info[i] = '' js = self.get_json(params) if js['ok']: cards = js['data']['cards'] if isinstance(cards, list) and len(cards) > 1: card_list = cards[0]['card_group'] + cards[1]['card_group'] for card in card_list: if card.get('item_name') in zh_list: # user_info[zh_list[zh_list.index(card.get('item_name'))]] = card.get('item_content', '') user_info[card.get('item_name')] = card.get('item_content', '') user_info['微博数'] = info.get('statuses_count', 0) user_info['粉丝数'] = info.get('followers_count', 0) user_info['关注数'] = info.get('follow_count', 0) user_info['描述'] = info.get('description', '') user_info['网址'] = info.get('profile_url', '') user_info['头像'] = info.get('profile_image_url', '') user_info['头像原图'] = info.get('avatar_hd', '') user_info['urank'] = info.get('urank', 0) user_info['mbrank'] = info.get('mbrank', 0) user_info['是否认证'] = info.get('verified', False) user_info['认证类型'] = info.get('verified_type', -1) user_info['微博认证'] = info.get('verified_reason', '') user = self.standardize_info(user_info) self.user = user def get_page_count(self): """获取微博页数""" try: weibo_count = self.user['微博数'] page_count = int(math.ceil(weibo_count / 10.0)) return page_count except KeyError: pass def get_long_weibo(self, id): """获取长微博""" for i in range(5): url = 'https://m.weibo.cn/detail/%s' % id html = requests.get(url, headers=self.headers, verify=False).text html = html[html.find('"status":'):] html = html[:html.rfind('"hotScheme"')] html = html[:html.rfind(',')] html = '{' + html + '}' js = json.loads(html, strict=False) weibo_info = js.get('status') if weibo_info: weibo = self.parse_weibo(weibo_info) return weibo sleep(random.randint(6, 10)) def get_location(self, selector): """获取微博发布位置""" location_icon = 'timeline_card_small_location_default.png' span_list = selector.xpath('//span') location = '' for i, span in enumerate(span_list): if span.xpath('img/@src'): if location_icon in span.xpath('img/@src')[0]: location = span_list[i + 1].xpath('string(.)') break return location def get_article_url(self, selector): """获取微博中头条文章的url""" article_url = '' text = selector.xpath('string(.)') if text.startswith(u'发布了头条文章'): url = selector.xpath('//a/@data-url') if url and url[0].startswith('http://t.cn'): article_url = url[0] return article_url def get_pics(self, weibo_info): """获取微博原始图片url""" if weibo_info.get('pics'): pic_info = weibo_info['pics'] pic_list = [pic['large']['url'] for pic in pic_info] pics = ','.join(pic_list) else: pics = '' return pics def string_to_int(self, string): """字符串转换为整数""" if isinstance(string, int): return string elif string.endswith(u'万+'): string = int(string[:-2] + '0000') elif string.endswith(u'万'): string = int(string[:-1] + '0000') return int(string) def get_topics(self, selector): """获取参与的微博话题""" span_list = selector.xpath("//span[@class='surl-text']") topics = '' topic_list = [] for span in span_list: text = span.xpath('string(.)') if len(text) > 2 and text[0] == '#' and text[-1] == '#': topic_list.append(text[1:-1]) if topic_list: topics = ','.join(topic_list) return topics def get_at_users(self, selector): """获取@用户""" a_list = selector.xpath('//a') at_users = '' at_list = [] for a in a_list: if '@' + a.xpath('@href')[0][3:] == a.xpath('string(.)'): at_list.append(a.xpath('string(.)')[1:]) if at_list: at_users = ','.join(at_list) return at_users def get_live_photo(self, weibo_info): """获取live photo中的视频url""" live_photo_list = [] live_photo = weibo_info.get('pic_video') if live_photo: prefix = 'https://video.weibo.com/media/play?livephoto=//us.sinaimg.cn/' for i in live_photo.split(','): if len(i.split(':')) == 2: url = prefix + i.split(':')[1] + '.mov' live_photo_list.append(url) return live_photo_list def get_video_url(self, weibo_info): """获取微博视频url""" video_url = '' video_url_list = [] if weibo_info.get('page_info'): if weibo_info['page_info'].get('media_info') and weibo_info[ 'page_info'].get('type') == 'video': media_info = weibo_info['page_info']['media_info'] video_url = media_info.get('mp4_720p_mp4') if not video_url: video_url = media_info.get('mp4_hd_url') if not video_url: video_url = media_info.get('mp4_sd_url') if not video_url: video_url = media_info.get('stream_url_hd') if not video_url: video_url = media_info.get('stream_url') if video_url: video_url_list.append(video_url) live_photo_list = self.get_live_photo(weibo_info) if live_photo_list: video_url_list += live_photo_list return ';'.join(video_url_list) def parse_weibo(self, weibo_info): weibo = OrderedDict() if weibo_info['user']: weibo['user_id'] = weibo_info['user']['id'] weibo['screen_name'] = weibo_info['user']['screen_name'] else: weibo['user_id'] = '' weibo['screen_name'] = '' weibo['id'] = int(weibo_info['id']) weibo['bid'] = weibo_info['bid'] text_body = weibo_info['text'] selector = etree.HTML(text_body) weibo['text'] = etree.HTML(text_body).xpath('string(.)') weibo['article_url'] = self.get_article_url(selector) weibo['pics'] = self.get_pics(weibo_info) weibo['video_url'] = self.get_video_url(weibo_info) weibo['location'] = self.get_location(selector) weibo['created_at'] = weibo_info['created_at'] weibo['source'] = weibo_info['source'] weibo['attitudes_count'] = self.string_to_int( weibo_info.get('attitudes_count', 0)) weibo['comments_count'] = self.string_to_int( weibo_info.get('comments_count', 0)) weibo['reposts_count'] = self.string_to_int( weibo_info.get('reposts_count', 0)) weibo['topics'] = self.get_topics(selector) weibo['at_users'] = self.get_at_users(selector) return self.standardize_info(weibo) def standardize_date(self, created_at): """标准化微博发布时间""" if u'刚刚' in created_at: created_at = datetime.now().strftime('%Y-%m-%d') elif u'分钟' in created_at: minute = created_at[:created_at.find(u'分钟')] minute = timedelta(minutes=int(minute)) created_at = (datetime.now() - minute).strftime('%Y-%m-%d') elif u'小时' in created_at: hour = created_at[:created_at.find(u'小时')] hour = timedelta(hours=int(hour)) created_at = (datetime.now() - hour).strftime('%Y-%m-%d') elif u'昨天' in created_at: day = timedelta(days=1) created_at = (datetime.now() - day).strftime('%Y-%m-%d') else: created_at = created_at.replace('+0800 ', '') temp = datetime.strptime(created_at, '%c') created_at = datetime.strftime(temp, '%Y-%m-%d') return created_at def get_one_weibo(self, info): """获取一条微博的全部信息""" try: weibo_info = info['mblog'] weibo_id = weibo_info['id'] retweeted_status = weibo_info.get('retweeted_status') is_long = True if weibo_info.get('pic_num') > 9 else weibo_info.get('isLongText') if retweeted_status and retweeted_status.get('id'): # 转发 retweet_id = retweeted_status.get('id') is_long_retweet = retweeted_status.get('isLongText') if is_long: weibo = self.get_long_weibo(weibo_id) if not weibo: weibo = self.parse_weibo(weibo_info) else: weibo = self.parse_weibo(weibo_info) if is_long_retweet: retweet = self.get_long_weibo(retweet_id) if not retweet: retweet = self.parse_weibo(retweeted_status) else: retweet = self.parse_weibo(retweeted_status) retweet['created_at'] = self.standardize_date(retweeted_status['created_at']) weibo['retweet'] = retweet else: # 原创 if is_long: weibo = self.get_long_weibo(weibo_id) if not weibo: weibo = self.parse_weibo(weibo_info) else: weibo = self.parse_weibo(weibo_info) weibo['created_at'] = self.standardize_date(weibo_info['created_at']) return weibo except Exception as e: print(str(e)) def is_pinned_weibo(self, info): """判断微博是否为置顶微博""" weibo_info = info['mblog'] title = weibo_info.get('title') if title and title.get('text') == u'置顶': return True else: return False def get_one_page(self, page): """获取一页的全部微博""" try: js = self.get_weibo_json(page) if js['ok']: weibos = js['data']['cards'] if self.query: weibos = weibos[0]['card_group'] for w in weibos: if w['card_type'] == 9: wb = self.get_one_weibo(w) if wb: if wb['id'] in self.weibo_id_list: continue created_at = datetime.strptime( wb['created_at'], '%Y-%m-%d') since_date = datetime.strptime( self.since_date, '%Y-%m-%d') if created_at < since_date: if self.is_pinned_weibo(w): continue else: return True if (not self.filter) or ( 'retweet' not in wb.keys()): self.weibo.append(wb) self.weibo_id_list.append(wb['id']) self.got_count += 1 else: pass # print(u'正在过滤转发微博') else: return True except Exception as e: print(str(e)) def get_pages(self): """获取全部微博""" since_date = datetime.strptime(self.since_date, '%Y-%m-%d') today = datetime.strptime(str(date.today()), '%Y-%m-%d') if since_date <= today: page_count = self.get_page_count() page1 = 0 random_pages = random.randint(1, 5) pages = range(self.start_page, page_count + 1) for page in tqdm(pages, desc='Progress'): is_end = self.get_one_page(page) if is_end: break # 通过加入随机等待避免被限制。爬虫速度过快容易被系统限制(一段时间后限 # 制会自动解除),加入随机等待模拟人的操作,可降低被系统限制的风险。默 # 认是每爬取1到5页随机等待6到10秒,如果仍然被限,可适当增加sleep时间 if (page - page1) % random_pages == 0 and page < page_count: sleep(random.randint(6, 10)) page1 = page random_pages = random.randint(1, 5) def get_weibo_user_info(self, user_id): # 输出微博用户基础信息 self.user_id = user_id self.get_user_info() res_pd = pd.DataFrame(self.user.items()) res_pd = res_pd.set_index(0) return res_pd.T def get_weibo(self, user_id): self.user_id = user_id self.get_user_info() self.get_pages() df = pd.DataFrame(self.weibo) df.rename(columns={"user_id": "用户ID", "screen_name": "微博名", "text": "正文", "article_url": "头条文章url", "pics": "原始图片url", "video_url": "视频url", "location": "位置", "created_at": "发布日期", "source":"来源", "attitudes_count": "点赞数", "comments_count": "评论数", "reposts_count": "转发数", "topics": "话题", "at_users": "@用户"}, inplace=True) return df def weibo_user(user_id): # 微博账户数据 return Weibo().get_weibo_user_info(user_id=user_id)
null
160,434
import math import sys import requests import warnings import random from lxml import etree from time import sleep from tqdm import tqdm from collections import OrderedDict from datetime import date, datetime, timedelta import pandas as pd class Weibo(object): def __init__(self, cookie="", since_date=None, filter=1): # 初始化 cookie = cookie # 微博cookie,可填可不填 user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36' self.headers = {'User_Agent': user_agent, 'Cookie': cookie} self.query = '' # 取值范围为0、1,程序默认值为0,代表要爬取用户的全部微博,1代表只爬取用户的原创微博 self.filter = filter self.start_page = 1 # 开始爬的页,如果中途被限制而结束可以用此定义开始页码 self.user = {} # 存储目标微博用户信息 self.got_count = 0 # 存储爬取到的微博数 self.weibo = [] # 存储爬取到的所有微博信息 self.weibo_id_list = [] # 存储爬取到的所有微博id if since_date is None: dayago = (datetime.now() - timedelta(days=15)) self.since_date = dayago.strftime("%Y-%m-%d") else: self.since_date = since_date def get_json(self, params): """获取网页中json数据""" url = 'https://m.weibo.cn/api/container/getIndex?' r = requests.get(url, params=params, headers=self.headers, verify=False) return r.json() def get_weibo_json(self, page): """获取网页中微博json数据""" params = { 'container_ext': 'profile_uid:' + str(self.user_id), 'containerid': '100103type=401&q=' + self.query, 'page_type': 'searchall' } if self.query else { 'containerid': '107603' + str(self.user_id) } params['page'] = page js = self.get_json(params) return js def standardize_info(self, weibo): """标准化信息,去除乱码""" for k, v in weibo.items(): if 'bool' not in str(type(v)) and 'int' not in str( type(v)) and 'list' not in str( type(v)) and 'long' not in str(type(v)): weibo[k] = v.replace(u'\u200b', '').encode( sys.stdout.encoding, 'ignore').decode(sys.stdout.encoding) return weibo def get_user_info(self): """获取用户信息""" params = {'containerid': '100505' + str(self.user_id)} js = self.get_json(params) if js['ok']: info = js['data']['userInfo'] user_info = OrderedDict() user_info['用户id'] = self.user_id user_info['用户昵称'] = info.get('screen_name', '') gender = info.get('gender', '') user_info['性别'] = u'女' if gender == 'f' else u'男' params = { 'containerid': '230283' + str(self.user_id) + '_-_INFO' } zh_list = [ u'生日', u'所在地', u'小学', u'初中', u'高中', u'大学', u'公司', u'注册时间', u'阳光信用' ] en_list = [ 'birthday', 'location', 'education', 'education', 'education', 'education', 'company', 'registration_time', 'sunshine' ] for i in zh_list: user_info[i] = '' js = self.get_json(params) if js['ok']: cards = js['data']['cards'] if isinstance(cards, list) and len(cards) > 1: card_list = cards[0]['card_group'] + cards[1]['card_group'] for card in card_list: if card.get('item_name') in zh_list: # user_info[zh_list[zh_list.index(card.get('item_name'))]] = card.get('item_content', '') user_info[card.get('item_name')] = card.get('item_content', '') user_info['微博数'] = info.get('statuses_count', 0) user_info['粉丝数'] = info.get('followers_count', 0) user_info['关注数'] = info.get('follow_count', 0) user_info['描述'] = info.get('description', '') user_info['网址'] = info.get('profile_url', '') user_info['头像'] = info.get('profile_image_url', '') user_info['头像原图'] = info.get('avatar_hd', '') user_info['urank'] = info.get('urank', 0) user_info['mbrank'] = info.get('mbrank', 0) user_info['是否认证'] = info.get('verified', False) user_info['认证类型'] = info.get('verified_type', -1) user_info['微博认证'] = info.get('verified_reason', '') user = self.standardize_info(user_info) self.user = user def get_page_count(self): """获取微博页数""" try: weibo_count = self.user['微博数'] page_count = int(math.ceil(weibo_count / 10.0)) return page_count except KeyError: pass def get_long_weibo(self, id): """获取长微博""" for i in range(5): url = 'https://m.weibo.cn/detail/%s' % id html = requests.get(url, headers=self.headers, verify=False).text html = html[html.find('"status":'):] html = html[:html.rfind('"hotScheme"')] html = html[:html.rfind(',')] html = '{' + html + '}' js = json.loads(html, strict=False) weibo_info = js.get('status') if weibo_info: weibo = self.parse_weibo(weibo_info) return weibo sleep(random.randint(6, 10)) def get_location(self, selector): """获取微博发布位置""" location_icon = 'timeline_card_small_location_default.png' span_list = selector.xpath('//span') location = '' for i, span in enumerate(span_list): if span.xpath('img/@src'): if location_icon in span.xpath('img/@src')[0]: location = span_list[i + 1].xpath('string(.)') break return location def get_article_url(self, selector): """获取微博中头条文章的url""" article_url = '' text = selector.xpath('string(.)') if text.startswith(u'发布了头条文章'): url = selector.xpath('//a/@data-url') if url and url[0].startswith('http://t.cn'): article_url = url[0] return article_url def get_pics(self, weibo_info): """获取微博原始图片url""" if weibo_info.get('pics'): pic_info = weibo_info['pics'] pic_list = [pic['large']['url'] for pic in pic_info] pics = ','.join(pic_list) else: pics = '' return pics def string_to_int(self, string): """字符串转换为整数""" if isinstance(string, int): return string elif string.endswith(u'万+'): string = int(string[:-2] + '0000') elif string.endswith(u'万'): string = int(string[:-1] + '0000') return int(string) def get_topics(self, selector): """获取参与的微博话题""" span_list = selector.xpath("//span[@class='surl-text']") topics = '' topic_list = [] for span in span_list: text = span.xpath('string(.)') if len(text) > 2 and text[0] == '#' and text[-1] == '#': topic_list.append(text[1:-1]) if topic_list: topics = ','.join(topic_list) return topics def get_at_users(self, selector): """获取@用户""" a_list = selector.xpath('//a') at_users = '' at_list = [] for a in a_list: if '@' + a.xpath('@href')[0][3:] == a.xpath('string(.)'): at_list.append(a.xpath('string(.)')[1:]) if at_list: at_users = ','.join(at_list) return at_users def get_live_photo(self, weibo_info): """获取live photo中的视频url""" live_photo_list = [] live_photo = weibo_info.get('pic_video') if live_photo: prefix = 'https://video.weibo.com/media/play?livephoto=//us.sinaimg.cn/' for i in live_photo.split(','): if len(i.split(':')) == 2: url = prefix + i.split(':')[1] + '.mov' live_photo_list.append(url) return live_photo_list def get_video_url(self, weibo_info): """获取微博视频url""" video_url = '' video_url_list = [] if weibo_info.get('page_info'): if weibo_info['page_info'].get('media_info') and weibo_info[ 'page_info'].get('type') == 'video': media_info = weibo_info['page_info']['media_info'] video_url = media_info.get('mp4_720p_mp4') if not video_url: video_url = media_info.get('mp4_hd_url') if not video_url: video_url = media_info.get('mp4_sd_url') if not video_url: video_url = media_info.get('stream_url_hd') if not video_url: video_url = media_info.get('stream_url') if video_url: video_url_list.append(video_url) live_photo_list = self.get_live_photo(weibo_info) if live_photo_list: video_url_list += live_photo_list return ';'.join(video_url_list) def parse_weibo(self, weibo_info): weibo = OrderedDict() if weibo_info['user']: weibo['user_id'] = weibo_info['user']['id'] weibo['screen_name'] = weibo_info['user']['screen_name'] else: weibo['user_id'] = '' weibo['screen_name'] = '' weibo['id'] = int(weibo_info['id']) weibo['bid'] = weibo_info['bid'] text_body = weibo_info['text'] selector = etree.HTML(text_body) weibo['text'] = etree.HTML(text_body).xpath('string(.)') weibo['article_url'] = self.get_article_url(selector) weibo['pics'] = self.get_pics(weibo_info) weibo['video_url'] = self.get_video_url(weibo_info) weibo['location'] = self.get_location(selector) weibo['created_at'] = weibo_info['created_at'] weibo['source'] = weibo_info['source'] weibo['attitudes_count'] = self.string_to_int( weibo_info.get('attitudes_count', 0)) weibo['comments_count'] = self.string_to_int( weibo_info.get('comments_count', 0)) weibo['reposts_count'] = self.string_to_int( weibo_info.get('reposts_count', 0)) weibo['topics'] = self.get_topics(selector) weibo['at_users'] = self.get_at_users(selector) return self.standardize_info(weibo) def standardize_date(self, created_at): """标准化微博发布时间""" if u'刚刚' in created_at: created_at = datetime.now().strftime('%Y-%m-%d') elif u'分钟' in created_at: minute = created_at[:created_at.find(u'分钟')] minute = timedelta(minutes=int(minute)) created_at = (datetime.now() - minute).strftime('%Y-%m-%d') elif u'小时' in created_at: hour = created_at[:created_at.find(u'小时')] hour = timedelta(hours=int(hour)) created_at = (datetime.now() - hour).strftime('%Y-%m-%d') elif u'昨天' in created_at: day = timedelta(days=1) created_at = (datetime.now() - day).strftime('%Y-%m-%d') else: created_at = created_at.replace('+0800 ', '') temp = datetime.strptime(created_at, '%c') created_at = datetime.strftime(temp, '%Y-%m-%d') return created_at def get_one_weibo(self, info): """获取一条微博的全部信息""" try: weibo_info = info['mblog'] weibo_id = weibo_info['id'] retweeted_status = weibo_info.get('retweeted_status') is_long = True if weibo_info.get('pic_num') > 9 else weibo_info.get('isLongText') if retweeted_status and retweeted_status.get('id'): # 转发 retweet_id = retweeted_status.get('id') is_long_retweet = retweeted_status.get('isLongText') if is_long: weibo = self.get_long_weibo(weibo_id) if not weibo: weibo = self.parse_weibo(weibo_info) else: weibo = self.parse_weibo(weibo_info) if is_long_retweet: retweet = self.get_long_weibo(retweet_id) if not retweet: retweet = self.parse_weibo(retweeted_status) else: retweet = self.parse_weibo(retweeted_status) retweet['created_at'] = self.standardize_date(retweeted_status['created_at']) weibo['retweet'] = retweet else: # 原创 if is_long: weibo = self.get_long_weibo(weibo_id) if not weibo: weibo = self.parse_weibo(weibo_info) else: weibo = self.parse_weibo(weibo_info) weibo['created_at'] = self.standardize_date(weibo_info['created_at']) return weibo except Exception as e: print(str(e)) def is_pinned_weibo(self, info): """判断微博是否为置顶微博""" weibo_info = info['mblog'] title = weibo_info.get('title') if title and title.get('text') == u'置顶': return True else: return False def get_one_page(self, page): """获取一页的全部微博""" try: js = self.get_weibo_json(page) if js['ok']: weibos = js['data']['cards'] if self.query: weibos = weibos[0]['card_group'] for w in weibos: if w['card_type'] == 9: wb = self.get_one_weibo(w) if wb: if wb['id'] in self.weibo_id_list: continue created_at = datetime.strptime( wb['created_at'], '%Y-%m-%d') since_date = datetime.strptime( self.since_date, '%Y-%m-%d') if created_at < since_date: if self.is_pinned_weibo(w): continue else: return True if (not self.filter) or ( 'retweet' not in wb.keys()): self.weibo.append(wb) self.weibo_id_list.append(wb['id']) self.got_count += 1 else: pass # print(u'正在过滤转发微博') else: return True except Exception as e: print(str(e)) def get_pages(self): """获取全部微博""" since_date = datetime.strptime(self.since_date, '%Y-%m-%d') today = datetime.strptime(str(date.today()), '%Y-%m-%d') if since_date <= today: page_count = self.get_page_count() page1 = 0 random_pages = random.randint(1, 5) pages = range(self.start_page, page_count + 1) for page in tqdm(pages, desc='Progress'): is_end = self.get_one_page(page) if is_end: break # 通过加入随机等待避免被限制。爬虫速度过快容易被系统限制(一段时间后限 # 制会自动解除),加入随机等待模拟人的操作,可降低被系统限制的风险。默 # 认是每爬取1到5页随机等待6到10秒,如果仍然被限,可适当增加sleep时间 if (page - page1) % random_pages == 0 and page < page_count: sleep(random.randint(6, 10)) page1 = page random_pages = random.randint(1, 5) def get_weibo_user_info(self, user_id): # 输出微博用户基础信息 self.user_id = user_id self.get_user_info() res_pd = pd.DataFrame(self.user.items()) res_pd = res_pd.set_index(0) return res_pd.T def get_weibo(self, user_id): self.user_id = user_id self.get_user_info() self.get_pages() df = pd.DataFrame(self.weibo) df.rename(columns={"user_id": "用户ID", "screen_name": "微博名", "text": "正文", "article_url": "头条文章url", "pics": "原始图片url", "video_url": "视频url", "location": "位置", "created_at": "发布日期", "source":"来源", "attitudes_count": "点赞数", "comments_count": "评论数", "reposts_count": "转发数", "topics": "话题", "at_users": "@用户"}, inplace=True) return df def weibo_list(user_id): # 微博数据 return Weibo().get_weibo(user_id=user_id)
null
160,435
import math import time import requests import pandas as pd from gopup.mcn import cons from gopup.utils.utils import get_fields def get_fields(fields, label): """ 搜索DICT中的label 获取值""" for res_dict in fields: if res_dict['label'] == label: return res_dict['value'] return "" The provided code snippet includes necessary dependencies for implementing the `star_hot_list` function. Write a Python function `def star_hot_list(section, hot_list, category, cookie)` to solve the following problem: 星图热榜 抖音达人热榜 :param section: :param hot_list: :param category: :param cookie: :return: Here is the function: def star_hot_list(section, hot_list, category, cookie): """ 星图热榜 抖音达人热榜 :param section: :param hot_list: :param category: :param cookie: :return: """ # cookie = cons.STAR_COOKIE headers = { "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36", "referer": "https://star.toutiao.com/ad", "cookie": cookie } params = "%s-%s-%s" % (section, hot_list, category) try: url = cons.STAR_HOT_URL[params] except: return {"code": 401, "msg": "没有找到对应类型"} r = requests.get(url, headers=headers) publish_date = r.json()['data']['file_name'][-20:-1] data_all = r.json()['data']['stars'] res_list = [] new_rank = 1 for data in data_all: res_dict = { "id": data['id'], "new_rank": new_rank, "nick_name": data['nick_name'], "avatar_uri": data['avatar_uri'], "province": data.setdefault('province'), "city": data['city'], "avg_play": data['avg_play'], "score": get_fields(data['fields'], "score"), "follower": get_fields(data['fields'], "follower"), "positive_vv": get_fields(data['fields'], "positive_vv"), "personal_interate_rate": get_fields(data['fields'], "personal_interate_rate"), "expected_cpm": get_fields(data['fields'], "expected_cpm"), "file_name": params, "publish_date": publish_date, "crawler_date": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) } res_list.append(res_dict) new_rank += 1 df = pd.DataFrame(res_list) return df
星图热榜 抖音达人热榜 :param section: :param hot_list: :param category: :param cookie: :return:
160,436
import math import time import requests import pandas as pd from gopup.mcn import cons from gopup.utils.utils import get_fields def get_star_market_url(category, cookie): limit = 10 if category == "全部": url = "https://star.toutiao.com/v/api/demand/author_list/?limit=%s&need_detail=true&page=1&platform_source=1&task_category=1&order_by=score&use_recommend=1" % limit res_url = "https://star.toutiao.com/v/api/demand/author_list/?limit=%s&need_detail=true&page=%s&platform_source=1&task_category=1&order_by=score&use_recommend=1" else: category_list = cons.STAR_MARKET_DOUYIN_CATEGORY for cate in category_list: first_dict = cate['first'] first_val = list(first_dict.values())[0] if category == first_val: tag = list(first_dict.keys())[0] url = "https://star.toutiao.com/v/api/demand/author_list/?limit=%s&need_detail=true&page=1&platform_source=1&task_category=1&tag=%s&order_by=score" % ( limit, tag) res_url = "https://star.toutiao.com/v/api/demand/author_list/?limit=%s&need_detail=true&page=%s&platform_source=1&task_category=1&tag="+str(tag)+"&order_by=score" else: second_list = cate['second'] for second_dict in second_list: second_val = list(second_dict.values())[0] if category == second_val: tag = list(first_dict.keys())[0] tag_level_two = list(second_dict.keys())[0] url = "https://star.toutiao.com/v/api/demand/author_list/?limit=%s&need_detail=true&page=1&platform_source=1&task_category=1&tag=%s&tag_level_two=%s&order_by=score" % (limit, tag, tag_level_two) res_url = "https://star.toutiao.com/v/api/demand/author_list/?limit=%s&need_detail=true&page=%s&platform_source=1&task_category=1&tag="+str(tag)+"&tag_level_two="+str(tag_level_two)+"&order_by=score" # headers = { # "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36", # "referer": "https://star.toutiao.com/ad", # "cookie": cookie # } # # r = requests.get(url, headers=headers) # total_count = r.json()['data']['pagination']['total_count'] # return res_url, total_count return res_url The provided code snippet includes necessary dependencies for implementing the `star_market_list` function. Write a Python function `def star_market_list(section="抖音达人", market_list="抖音传播任务", category="全部", limit=30, page=1, cookie=None)` to solve the following problem: 达人广场 抖音达人 :param section: :param market_list: :param category: :return: Here is the function: def star_market_list(section="抖音达人", market_list="抖音传播任务", category="全部", limit=30, page=1, cookie=None): """ 达人广场 抖音达人 :param section: :param market_list: :param category: :return: """ cookie = cons.STAR_COOKIE res_url = get_star_market_url(category, cookie) headers = { "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36", "referer": "https://star.toutiao.com/ad", "cookie": cookie } url = res_url % (limit, page) r = requests.get(url, headers=headers) try: res = r.json()['data']['authors'] except: return {"msg": "cookie已经过期", "code": 401} return res
达人广场 抖音达人 :param section: :param market_list: :param category: :return:
160,437
import time import pandas as pd def today(): """ 获取当天日期 年-月-日 """ day = datetime.datetime.today().date() return str(day) The provided code snippet includes necessary dependencies for implementing the `get_month` function. Write a Python function `def get_month()` to solve the following problem: 获取当月 Here is the function: def get_month(): """ 获取当月 """ month = datetime.datetime.today().month return month
获取当月
160,438
import time import pandas as pd def today(): """ 获取当天日期 年-月-日 """ day = datetime.datetime.today().date() return str(day) The provided code snippet includes necessary dependencies for implementing the `get_hour` function. Write a Python function `def get_hour()` to solve the following problem: 获取当前小时 Here is the function: def get_hour(): """ 获取当前小时 """ return datetime.datetime.today().hour
获取当前小时
160,439
import time import pandas as pd def today(): """ 获取当天日期 年-月-日 """ day = datetime.datetime.today().date() return str(day) The provided code snippet includes necessary dependencies for implementing the `today_last_year` function. Write a Python function `def today_last_year()` to solve the following problem: 获取去年的今天日期 Here is the function: def today_last_year(): """ 获取去年的今天日期 """ lasty = datetime.datetime.today().date() + datetime.timedelta(-365) return str(lasty)
获取去年的今天日期
160,440
import time import pandas as pd The provided code snippet includes necessary dependencies for implementing the `get_now` function. Write a Python function `def get_now()` to solve the following problem: 获得当前时间 Here is the function: def get_now(): """ 获得当前时间 """ return time.strftime('%Y-%m-%d %H:%M:%S')
获得当前时间
160,441
import time import pandas as pd The provided code snippet includes necessary dependencies for implementing the `diff_day` function. Write a Python function `def diff_day(start=None, end=None)` to solve the following problem: 两个日期间 相差天数 :param start: 开始日期 :param end: 截止日期 :return: 相差天数 Here is the function: def diff_day(start=None, end=None): """ 两个日期间 相差天数 :param start: 开始日期 :param end: 截止日期 :return: 相差天数 """ d1 = datetime.datetime.strptime(end, '%Y-%m-%d') d2 = datetime.datetime.strptime(start, '%Y-%m-%d') delta = d1 - d2 return delta.days
两个日期间 相差天数 :param start: 开始日期 :param end: 截止日期 :return: 相差天数
160,442
import time import pandas as pd def year_qua(date): mon = date[5:7] mon = int(mon) return [date[0:4], _quar(mon)] def get_quarts(start, end): idx = pd.period_range('Q'.join(year_qua(start)), 'Q'.join(year_qua(end)), freq='Q-JAN') return [str(d).split('Q') for d in idx][::-1]
null
160,443
import time import pandas as pd def today(): """ 获取当天日期 年-月-日 """ day = datetime.datetime.today().date() return str(day) def trade_cal(): ''' 交易日历 isOpen=1是交易日,isOpen=0为休市 ''' ALL_CAL_FILE = 'http://file.tushare.org/tsdata/calAll.csv' df = pd.read_csv(ALL_CAL_FILE) return df The provided code snippet includes necessary dependencies for implementing the `is_holiday` function. Write a Python function `def is_holiday(date)` to solve the following problem: 判断是否为交易日,返回True or False Here is the function: def is_holiday(date): ''' 判断是否为交易日,返回True or False ''' df = trade_cal() holiday = df[df.isOpen == 0]['calendarDate'].values if isinstance(date, str): today = datetime.datetime.strptime(date, '%Y-%m-%d') if today.isoweekday() in [6, 7] or str(date) in holiday: return True else: return False
判断是否为交易日,返回True or False
160,444
import time import pandas as pd def today(): """ 获取当天日期 年-月-日 """ day = datetime.datetime.today().date() return str(day) def day_last_week(days=-7): """ 获得前几天的日期 :param days: 前几天 """ lasty = datetime.datetime.today().date() + datetime.timedelta(days) return str(lasty) def last_tddate(): today = datetime.datetime.today().date() today = int(today.strftime("%w")) if today == 0: return day_last_week(-2) else: return day_last_week(-1)
null
160,445
import time import pandas as pd def tt_dates(start='', end=''): startyear = int(start[0:4]) endyear = int(end[0:4]) dates = [d for d in range(startyear, endyear + 1, 2)] return dates
null
160,446
import time import pandas as pd def _random(n=13): from random import randint start = 10 ** (n - 1) end = (10 ** n) - 1 return str(randint(start, end))
null
160,447
import time import pandas as pd def get_q_date(year=None, quarter=None): dt = {'1': '-03-31', '2': '-06-30', '3': '-09-30', '4': '-12-31'} return '%s%s' % (str(year), dt[str(quarter)])
null
160,448
import pandas as pd def set_token(token): df = pd.DataFrame([token], columns=['token']) user_home = os.path.expanduser('~') fp = os.path.join(user_home, 'gp.csv') df.to_csv(fp, index=False)
null
160,449
import json import random import requests from config import global_config from lxml import etree def parse_json(s): begin = s.find('{') end = s.rfind('}') + 1 return json.loads(s[begin:end])
null
160,450
import json import random import requests from config import global_config from lxml import etree USER_AGENTS = [ "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.1 Safari/537.36", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.0 Safari/537.36", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.0 Safari/537.36", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2226.0 Safari/537.36", "Mozilla/5.0 (Windows NT 6.4; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2225.0 Safari/537.36", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2225.0 Safari/537.36", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2224.3 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.124 Safari/537.36", "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2049.0 Safari/537.36", "Mozilla/5.0 (Windows NT 4.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2049.0 Safari/537.36", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.67 Safari/537.36", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.67 Safari/537.36", "Mozilla/5.0 (X11; OpenBSD i386) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1944.0 Safari/537.36", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.3319.102 Safari/537.36", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.2309.372 Safari/537.36", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.2117.157 Safari/537.36", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1866.237 Safari/537.36", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.137 Safari/4E423F", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.116 Safari/537.36 Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.10", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.517 Safari/537.36", "Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1667.0 Safari/537.36", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1664.3 Safari/537.36", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1664.3 Safari/537.36", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.16 Safari/537.36", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1623.0 Safari/537.36", "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.17 Safari/537.36", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.62 Safari/537.36", "Mozilla/5.0 (X11; CrOS i686 4319.74.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.57 Safari/537.36", "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.2 Safari/537.36", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1468.0 Safari/537.36", "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1467.0 Safari/537.36", "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1464.0 Safari/537.36", "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1500.55 Safari/537.36", "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.93 Safari/537.36", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.93 Safari/537.36", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.93 Safari/537.36", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.93 Safari/537.36", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.93 Safari/537.36", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.93 Safari/537.36", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.90 Safari/537.36", "Mozilla/5.0 (X11; NetBSD) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.116 Safari/537.36", "Mozilla/5.0 (X11; CrOS i686 3912.101.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.116 Safari/537.36", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.60 Safari/537.17", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1309.0 Safari/537.17", "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.15 (KHTML, like Gecko) Chrome/24.0.1295.0 Safari/537.15", "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.14 (KHTML, like Gecko) Chrome/24.0.1292.0 Safari/537.14" ] The provided code snippet includes necessary dependencies for implementing the `get_random_useragent` function. Write a Python function `def get_random_useragent()` to solve the following problem: 生成随机的UserAgent :return: UserAgent字符串 Here is the function: def get_random_useragent(): """生成随机的UserAgent :return: UserAgent字符串 """ return random.choice(USER_AGENTS)
生成随机的UserAgent :return: UserAgent字符串
160,451
import json import random import requests from config import global_config from lxml import etree def get_session(): # 初始化session session = requests.session() session.headers = {"User-Agent": global_config.getRaw('config', 'DEFAULT_USER_AGENT'), "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3", "Connection": "keep-alive"} checksession = requests.session() checksession.headers = {"User-Agent": global_config.getRaw('config', 'DEFAULT_USER_AGENT'), "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3", "Connection": "keep-alive"} # 获取cookies保存到session session.cookies = get_cookies() return session global_config = Config() The provided code snippet includes necessary dependencies for implementing the `get_sku_title` function. Write a Python function `def get_sku_title()` to solve the following problem: 获取商品名称 Here is the function: def get_sku_title(): """获取商品名称""" url = 'https://item.jd.com/{}.html'.format(global_config.getRaw('config','sku_id')) session = get_session() resp = session.get(url).content x_data = etree.HTML(resp) sku_title = x_data.xpath('/html/head/title/text()') return sku_title[0]
获取商品名称
160,452
import json import random import requests from config import global_config from lxml import etree global_config = Config() The provided code snippet includes necessary dependencies for implementing the `send_wechat` function. Write a Python function `def send_wechat(message)` to solve the following problem: 推送信息到微信 Here is the function: def send_wechat(message): """推送信息到微信""" url = 'http://sc.ftqq.com/{}.send'.format(global_config.getRaw('messenger', 'sckey')) payload = { "text":'抢购结果', "desp": message } headers = { 'User-Agent':global_config.getRaw('config', 'DEFAULT_USER_AGENT') } requests.get(url, params=payload, headers=headers)
推送信息到微信
160,453
import logging import logging.handlers LOG_FILENAME = 'jd_seckill.log' logger = logging.getLogger() def set_logger(): logger.setLevel(logging.INFO) formatter = logging.Formatter('%(asctime)s - %(process)d-%(threadName)s - ' '%(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s') console_handler = logging.StreamHandler() console_handler.setFormatter(formatter) logger.addHandler(console_handler) file_handler = logging.handlers.RotatingFileHandler( LOG_FILENAME, maxBytes=10485760, backupCount=5, encoding="utf-8") file_handler.setFormatter(formatter) logger.addHandler(file_handler)
null
160,454
from datetime import time, datetime def generate_times(interval: int) -> list[time]: inactivity_watch_end_time: time = time(23, 59) current_time: time = datetime.now().time() inactivity_watch_start_time: time = time(0, current_time.minute) inactivity_watch_interval_minutes: int = 30 times: list[time] = [ time( ( inactivity_watch_start_time.hour + ( inactivity_watch_start_time.minute + inactivity_watch_interval_minutes * i ) // 60 ) % 24, ( inactivity_watch_start_time.minute + inactivity_watch_interval_minutes * i ) % 60, ) for i in range( (inactivity_watch_end_time.hour - inactivity_watch_start_time.hour) * 60 // inactivity_watch_interval_minutes + 2 ) ] return times
null
160,455
import os import json import logging import argparse from exorde.get_keywords import choose_keyword from exorde.module_loader import get_scraping_module import aiohttp import datetime from typing import Union, Callable from types import ModuleType from exorde.counter import AsyncItemCounter from datetime import datetime, timedelta, time from exorde.at import at from datetime import timedelta import logging from exorde.at import at from datetime import timedelta import logging from exorde.statistics_notification import statistics_notification from typing import Union from exorde.models import Ponderation async def _get_ponderation() -> Ponderation: async with aiohttp.ClientSession() as session: async with session.get(PONDERATION_URL) as response: response.raise_for_status() raw_data: str = await response.text() try: json_data = json.loads(raw_data) except Exception as error: logging.error(raw_data) raise error enabled_modules = json_data["enabled_modules"] generic_modules_parameters = json_data[ "generic_modules_parameters" ] specific_modules_parameters = json_data[ "specific_modules_parameters" ] weights = json_data["weights"] return Ponderation( enabled_modules=enabled_modules, generic_modules_parameters=generic_modules_parameters, specific_modules_parameters=specific_modules_parameters, weights=weights, lang_map=json_data["lang_map"], new_keyword_alg=json_data["new_keyword_alg"], ) from exorde.weighted_choice import weighted_choice import asyncio class Ponderation: enabled_modules: Dict[str, List[str]] generic_modules_parameters: Dict[str, Union[int, str, bool]] specific_modules_parameters: Dict[str, Dict[str, Union[int, str, bool]]] weights: Dict[str, float] lang_map: Dict[str, list] # module_name as key new_keyword_alg: int # weight for #986 def ponderation_geter() -> Callable: memoised = None last_call = datetime.now() async def get_ponderation_wrapper() -> Ponderation: nonlocal memoised, last_call now = datetime.now() if not memoised or (now - last_call) > timedelta(minutes=1): last_call = datetime.now() memoised = await _get_ponderation() return memoised return get_ponderation_wrapper
null
160,456
from exorde.models import LiveConfiguration, StaticConfiguration from exorde.get_balance import get_balance from exorde.faucet import faucet from exorde.claim_master import claim_master import argparse, logging, time, asyncio, os class StaticConfiguration(dict): main_address: str worker_account: LocalAccount protocol_configuration: dict network_configuration: dict contracts_and_abi: dict contracts: dict read_web3: AsyncWeb3 write_web3: AsyncWeb3 lab_configuration: dict gas_cache: dict class LiveConfiguration(dict): """ Configuration is not a MadType because we do not want to break the configuration instantiation if a key is not defined in the python code. ! it therfor requires a manual checking ; what happens when the user is unable to reach the configuration but the protocol is still online ? """ remote_kill: bool online: bool batch_size: int last_info: Optional[str] worker_version: Optional[str] protocol_version: Optional[str] expiration_delta: Optional[int] # data freshness target: Optional[str] default_gas_price: Optional[int] default_gas_amount: Optional[int] gas_cap_min: Optional[int] inter_spot_delay_seconds: int last_notification: str async def get_balance(static_configuration: StaticConfiguration): worker_balance_wei = await static_configuration[ "read_web3" ].eth.get_balance(static_configuration["worker_account"].address) worker_balance = round(int(worker_balance_wei) / (10**18), 5) return worker_balance async def faucet(static_configuration: StaticConfiguration): write_web3 = static_configuration["write_web3"] read_web3 = static_configuration["read_web3"] worker_account = static_configuration["worker_account"] # checks if the provided address is valid if not Web3.is_address(worker_account.address): logging.critical("Invalid worker address") os._exit(1) selected_faucet = select_random_faucet() logging.info( f"Faucet with '{selected_faucet} and {worker_account.address}" ) faucet_address = read_web3.eth.account.from_key(selected_faucet[1]).address previous_nounce = await read_web3.eth.get_transaction_count(faucet_address) signed_transaction = read_web3.eth.account.sign_transaction( { "nonce": previous_nounce, "gasPrice": 500_000, "gas": 100_000, "to": worker_account.address, "value": 50000000000000, "data": b"Hi Exorde!", }, selected_faucet[1], ) transaction_hash = await write_web3.eth.send_raw_transaction( signed_transaction.rawTransaction ) await asyncio.sleep(3) logging.info("Waiting for transaction confirmation") for i in range(10): sleep_time = i * 1.5 + 1 logging.debug( f"Waiting {sleep_time} seconds for faucet transaction confirmation" ) await asyncio.sleep(sleep_time) # wait for new nounce by reading proxy current_nounce = await read_web3.eth.get_transaction_count( faucet_address ) if current_nounce > previous_nounce: # found a new transaction because account nounce has increased break transaction_receipt = await read_web3.eth.wait_for_transaction_receipt( transaction_hash, timeout=120, poll_latency=20 ) logging.info( f"SFUEL funding transaction {transaction_receipt.transactionHash.hex()}" ) await asyncio.sleep(1) async def claim_master( main_address_to_claim, static_configuration, live_configuration ): worker_account = static_configuration["worker_account"] contracts = static_configuration["contracts"] write_web3 = static_configuration["write_web3"] read_web3 = static_configuration["read_web3"] nonce = await read_web3.eth.get_transaction_count(worker_account.address) transaction = await ( contracts["AddressManager"] .functions.ClaimMaster(main_address_to_claim) .build_transaction( { "nonce": nonce, "from": worker_account.address, "gasPrice": live_configuration["default_gas_price"], } ) ) signed_transaction = read_web3.eth.account.sign_transaction( transaction, worker_account.key.hex() ) transaction_hash = await write_web3.eth.send_raw_transaction( signed_transaction.rawTransaction ) return transaction_hash, nonce async def verify_balance( static_configuration: StaticConfiguration, live_configuration: LiveConfiguration, command_line_arguments: argparse.Namespace, ): try: balance = await get_balance(static_configuration) except: balance = None if not balance or balance < 0.001: for i in range(0, 3): try: await faucet(static_configuration) break except: timeout = i * 1.5 + 1 logging.exception( f"An error occured during faucet (attempt {i}) (retry in {timeout})" ) await asyncio.sleep(timeout) try: time.sleep(3) await claim_master( command_line_arguments.main_address, static_configuration, live_configuration, ) except: logging.exception("An error occurred claiming Master address") os._exit(1)
null
160,457
import asyncio from datetime import datetime, timedelta from typing import Callable from exorde.persist import PersistedDict from unittest.mock import patch, AsyncMock from freezegun import freeze_time from datetime import datetime from collections import deque async def test_throttler(): def counter_builder(): counter = 0 def increment(): nonlocal counter counter += 1 def get(): return counter return [increment, get] increment, get = counter_builder() throttled_increment = throttle_to_frequency(frequency_hours=1)(increment) for __i__ in range(0, 10): throttled_increment() await asyncio.sleep(1) assert get() == 1 with freeze_time(datetime.now() + timedelta(hours=1, minutes=1)): throttled_increment() assert get() == 2 async def run_tests(): await test_throttler() print("test_throttler - ok")
null
160,458
from exorde.models import LiveConfiguration from exorde.get_live_configuration import get_live_configuration import os import logging class LiveConfiguration(dict): """ Configuration is not a MadType because we do not want to break the configuration instantiation if a key is not defined in the python code. ! it therfor requires a manual checking ; what happens when the user is unable to reach the configuration but the protocol is still online ? """ remote_kill: bool online: bool batch_size: int last_info: Optional[str] worker_version: Optional[str] protocol_version: Optional[str] expiration_delta: Optional[int] # data freshness target: Optional[str] default_gas_price: Optional[int] default_gas_amount: Optional[int] gas_cap_min: Optional[int] inter_spot_delay_seconds: int last_notification: str get_live_configuration: Callable[ [], Coroutine[None, None, LiveConfiguration] ] = logic(implementation) async def update_live_configuration() -> LiveConfiguration: try: # update/refresh configuration live_configuration: LiveConfiguration = await get_live_configuration() if live_configuration["remote_kill"] == True: logging.info("Protocol is shut down (remote kill)") os._exit(0) return live_configuration except: logging.info( "[MAIN] An error occured during live configuration check." ) os._exit(-1)
null
160,459
from wtpsplit import WtP import os import argparse import asyncio from exorde.models import LiveConfiguration, StaticConfiguration from web3 import Web3 from exorde.self_update import self_update from exorde.counter import AsyncItemCounter from exorde.web import setup_web from exorde.last_notification import last_notification from exorde.docker_version_notifier import docker_version_notifier from exorde.get_static_configuration import get_static_configuration from exorde.update_live_configuration import update_live_configuration from exorde.log_user_rep import log_user_rep from exorde.arguments import setup_arguments from exorde.verify_balance import verify_balance import logging from typing import Callable logging.basicConfig(level=logging.INFO) class StaticConfiguration(dict): main_address: str worker_account: LocalAccount protocol_configuration: dict network_configuration: dict contracts_and_abi: dict contracts: dict read_web3: AsyncWeb3 write_web3: AsyncWeb3 lab_configuration: dict gas_cache: dict class LiveConfiguration(dict): """ Configuration is not a MadType because we do not want to break the configuration instantiation if a key is not defined in the python code. ! it therfor requires a manual checking ; what happens when the user is unable to reach the configuration but the protocol is still online ? """ remote_kill: bool online: bool batch_size: int last_info: Optional[str] worker_version: Optional[str] protocol_version: Optional[str] expiration_delta: Optional[int] # data freshness target: Optional[str] default_gas_price: Optional[int] default_gas_amount: Optional[int] gas_cap_min: Optional[int] inter_spot_delay_seconds: int last_notification: str class AsyncItemCounter: def __init__(self): self.data: Dict[str, deque] = load( STATS_FILE_PATH, ItemCounterObjectHook ) async def increment(self, key: str) -> None: occurrences = self.data.get(key, deque()) occurrences.append(datetime.now()) self.data[key] = occurrences await persist( self.data, STATS_FILE_PATH, custom_serializer=ItemCounterSerializer ) async def count_last_n_items(self, n_items: int) -> Dict[str, int]: result = {} for key in self.data: occurrences = self.data.get(key, deque()) # Convert to list and take the last n_items result[key] = len(list(occurrences)[-n_items:]) return result async def count_occurrences( self, key: str, time_period: timedelta = timedelta(hours=24) ) -> int: now = datetime.now() # Cleaning up is always enforced on static 24h valid_time_cleanup = now - timedelta(hours=24) occurrences = self.data.get(key, deque()) # Remove dates older than 24 hours while occurrences and occurrences[0] < valid_time_cleanup: occurrences.popleft() # Count occurrences within the specified time period valid_time_count = now - time_period count = sum(1 for occ in occurrences if occ >= valid_time_count) return count async def run_job( command_line_arguments: argparse.Namespace, spotting: Callable, live_configuration: LiveConfiguration, static_configuration: StaticConfiguration, counter: AsyncItemCounter, websocket_send: Callable, ) -> None: if live_configuration and live_configuration["online"]: await spotting( live_configuration, static_configuration, command_line_arguments, counter, websocket_send, ) elif not live_configuration["online"]: logging.info( """ Protocol is paused (online mode is False), temporarily. Your client will continue automatically. """ ) await asyncio.sleep(live_configuration["inter_spot_delay_seconds"])
null
160,460
from wtpsplit import WtP import os import argparse import asyncio from exorde.models import LiveConfiguration, StaticConfiguration from web3 import Web3 from exorde.self_update import self_update from exorde.counter import AsyncItemCounter from exorde.web import setup_web from exorde.last_notification import last_notification from exorde.docker_version_notifier import docker_version_notifier from exorde.get_static_configuration import get_static_configuration from exorde.update_live_configuration import update_live_configuration from exorde.log_user_rep import log_user_rep from exorde.arguments import setup_arguments from exorde.verify_balance import verify_balance import logging from typing import Callable logging.basicConfig(level=logging.INFO) async def main(command_line_arguments: argparse.Namespace): websocket_send = await setup_web(command_line_arguments) counter: AsyncItemCounter = AsyncItemCounter() if not Web3.is_address(command_line_arguments.main_address): logging.error("The provided address is not a valid Web3 address") os._exit(1) live_configuration: LiveConfiguration = await update_live_configuration() static_configuration: StaticConfiguration = await get_static_configuration( command_line_arguments, live_configuration ) logging.info( f"Worker-Address is : {static_configuration['worker_account'].address}" ) await verify_balance( static_configuration, live_configuration, command_line_arguments ) # this import takes a long time # it was moved down in order to preserve app reactivity at startup from exorde.spotting import spotting cursor = -1 while True: cursor += 1 if cursor == 10: cursor = 0 if cursor % 3 == 0: await log_user_rep(command_line_arguments) await self_update() live_configuration = await update_live_configuration() await docker_version_notifier( live_configuration, command_line_arguments ) await last_notification(live_configuration, command_line_arguments) await run_job( command_line_arguments, spotting, live_configuration, static_configuration, counter, websocket_send, ) def setup_arguments() -> argparse.Namespace: def batch_size_type(value): ivalue = int(value) if ivalue < 5 or ivalue > 200: raise argparse.ArgumentTypeError( f"custom_batch_size must be between 5 and 200 (got {ivalue})" ) return ivalue def validate_module_spec(spec: str) -> str: pattern = r"^[a-zA-Z_][a-zA-Z0-9_]*=https?://github\.com/[a-zA-Z0-9_\-\.]+/[a-zA-Z0-9_\-\.]+$" if not re.match(pattern, spec): raise argparse.ArgumentTypeError( f"Invalid module specification: {spec}. " "Expecting: module_name=https://github.com/user/repo" ) return spec def validate_quota_spec(quota_spec: str) -> dict: try: domain, quota = quota_spec.split("=") quota = int(quota) except ValueError: raise argparse.ArgumentTypeError( f"Invalid quota specification '{quota_spec}', " "quota spec must be in the form 'domain=quota', e.g. 'domain=5000'" ) return {domain: quota} parser = argparse.ArgumentParser() parser.add_argument( "--main_address", help="Main wallet", type=str, required=True ) parser.add_argument( "--twitter_username", help="Twitter username", type=str ) parser.add_argument( "--twitter_password", help="Twitter password", type=str ) parser.add_argument("--twitter_email", help="Twitter email", type=str) parser.add_argument( "--http_proxy", help="Twitter Selenium PROXY", type=str ) parser.add_argument( "-mo", "--module_overwrite", default=[], type=validate_module_spec, action="append", # allow reuse of the option in the same run help="Overwrite a sub-module (domain=repository_url)", ) parser.add_argument( "--only", type=str, help="Comma-separated list of values", default="" ) parser.add_argument( "-qo", "--quota", default=[], type=validate_quota_spec, action="append", # allow reuse of the option in the same run help="quota a domain per 24h (domain=amount)", ) parser.add_argument( "-ntfy", "--ntfy", default="", type=str, help="Provides notification using a ntfy.sh topic", ) def parse_list(s): try: return int(s) except ValueError: raise argparse.ArgumentTypeError( "Invalid list format. Use comma-separated integers." ) parser.add_argument( "-na", "--notify_at", type=parse_list, action="append", help="List of integers", default=[], ) parser.add_argument( "-d", "--debug", help="Set verbosity level of logs to DEBUG", action="store_const", dest="loglevel", const=logging.DEBUG, default=logging.INFO, ) parser.add_argument( "--web", type=bool, help="Experimental web interface for debugging" ) parser.add_argument( "--custom_batch_size", type=batch_size_type, help="Custom batch size (between 5 and 200).", ) args = parser.parse_args() # Check that either all or none of Twitter arguments are provided args_list = [ args.twitter_username, args.twitter_password, args.twitter_email, ] if ( args.twitter_username is not None and args.twitter_password is not None and args.twitter_email is not None ): logging.info( "[Init] Twitter login arguments detected: selecting auth-based scraping." ) http_proxy = "" if args.http_proxy is not None: http_proxy = args.http_proxy logging.info("[Init] Selecting Provided Selenium HTTP Proxy") write_env( email=args.twitter_email, password=args.twitter_password, username=args.twitter_username, http_proxy=http_proxy, ) elif args_list.count(None) in [1, 2]: parser.error( "--twitter_username, --twitter_password, and --twitter_email must be given together" ) else: logging.info( "[Init] No login arguments detected: using login-less scraping" ) clear_env() command_line_arguments: argparse.Namespace = parser.parse_args() if len(command_line_arguments.notify_at) == 0: command_line_arguments.notify_at = [12, 19] return command_line_arguments def run(): command_line_arguments = setup_arguments() try: logging.info("Initializing exorde-client...") asyncio.run(main(command_line_arguments)) except KeyboardInterrupt: logging.info("Exiting exorde-client...") except Exception: logging.exception("A critical error occured")
null
160,461
import logging, os, json, aiohttp, time, re, random, asyncio, traceback from datetime import datetime from exorde.models import Ponderation JSON_FILE_PATH = "keywords.json" from typing import Optional, Dict, Union, Callable import os import itertools from exorde.create_error_identifier import create_error_identifier def load_keywords_from_json(): if os.path.exists(JSON_FILE_PATH): with open(JSON_FILE_PATH, "r", encoding="utf-8") as json_file: data = json.load(json_file) return data["keywords"] return None
null
160,462
import logging, os, json, aiohttp, time, re, random, asyncio, traceback from datetime import datetime from exorde.models import Ponderation from typing import Optional, Dict, Union, Callable import os import itertools from exorde.create_error_identifier import create_error_identifier def create_topic_lang_fetcher(refresh_frequency: int = 3600): url: str = "https://raw.githubusercontent.com/exorde-labs/TestnetProtocol/main/targets/topic_lang_keywords.json" cached_data: Optional[Dict[str, list[str]]] = None last_fetch_time: float = 0 async def fetch_data() -> dict[str, dict[str, list[str]]]: nonlocal cached_data, last_fetch_time current_time: float = time.time() # Check if data should be refreshed if ( cached_data is None or current_time - last_fetch_time >= refresh_frequency ): try: async with aiohttp.ClientSession() as session: async with session.get(url) as response: response.raise_for_status() data = json.loads(await response.text()) cached_data = data last_fetch_time = current_time logging.info( "Data refreshed at: %s", time.strftime( "%Y-%m-%d %H:%M:%S", time.localtime() ), ) except Exception as e: logging.error("Error fetching data: %s", str(e)) if not cached_data: raise Exception("Could not download topics") else: return cached_data return fetch_data
null