Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

tweak about Baseurl and socks5 proxy support #624

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 73 additions & 0 deletions examples/example2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
from pytrends.request import TrendReq
country_codes = [
'cy', 'pe', 'hk', 'co', 'mx', 'br', 'ua', 'ng', 'ph', 'au',
'tr', 'vn', 'tw', 'ar', 'gi', 'my', 'gh', 'ec', 'na', 'sb',
'ni', 'gt', 'pr', 'sg', 'bh', 'nf', 'pl', 'bo', 'ag', 'om',
'sa', 'bn', 'lb', 'pk', 'py', 'qa', 'ru', 'pa', 'cu', 'np',
'sl', 'do', 'sv', 'mt', 'eg', 'kw', 'et', 'ly', 'fj', 'jm',
'kh', 'uy', 'bd', 'mm', 'vc', 'af', 'tj', 'ai', 'bz', 'pg',
'by', 'iq', 'tn', 'ge', 'kz', 'gr', 'jo', 'nr', 've', 'lv',
'pt', 'dz', 'ht', 'gy', 'bi', 'ps', 'gp', 'am',''
]
# Only need to run this once, the rest of requests will use the same session.
country_codes = [
'vn', 'py', 'sv', 'eg', 'et', 'ly', 'fj', 'jm', 'uy', 'vc',
'af', 'tj', 'bz', 'pg', 'tn', 'gr'
]
for c in country_codes:

# print('try',c)
try:
pytrend = TrendReq(base_url=c
,proxies=['socks5h://127.0.0.1:1080']
)
pytrend.build_payload(kw_list=['ai'])

interest_over_time_df = pytrend.interest_over_time()
# print(interest_over_time_df.head())
print(c)
except :
# print('failed',c)
pass

# # Create payload and capture API tokens. Only needed for interest_over_time(), interest_by_region() & related_queries()
# pytrend.build_payload(kw_list=['pizza', 'bagel'])

# # Interest Over Time
interest_over_time_df = pytrend.interest_over_time()
print(interest_over_time_df.head())

# # Interest by Region
# interest_by_region_df = pytrend.interest_by_region()
# print(interest_by_region_df.head())

# # Related Queries, returns a dictionary of dataframes
# related_queries_dict = pytrend.related_queries()
# print(related_queries_dict)

# # Get Google Hot Trends data
# trending_searches_df = pytrend.trending_searches()
# print(trending_searches_df.head())

# # Get Google Hot Trends data
# today_searches_df = pytrend.today_searches()
# print(today_searches_df.head())

# # Get Google Top Charts
# top_charts_df = pytrend.top_charts(2018, hl='en-US', tz=300, geo='GLOBAL')
# print(top_charts_df.head())

# # Get Google Keyword Suggestions
# suggestions_dict = pytrend.suggestions(keyword='pizza')
# print(suggestions_dict)

# # Get Google Realtime Search Trends
# realtime_searches = pytrend.realtime_trending_searches(pn='IN')
# print(realtime_searches.head())

# # Recreate payload with multiple timeframes
# pytrend.build_payload(kw_list=['pizza', 'bagel'], timeframe=['2022-09-04 2022-09-10', '2022-09-18 2022-09-24'])

# # Multirange Interest Over Time
# multirange_interest_over_time_df = pytrend.multirange_interest_over_time()
# print(multirange_interest_over_time_df.head())
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"

[project]
name = "pytrends"
version = "4.9.2"
version = "4.9.3"
description = "Pseudo API for Google Trends"
urls = {homepage = "https://github.com/dreyco676/pytrends"}
requires-python = ">=3.7"
Expand Down
71 changes: 43 additions & 28 deletions pytrends/request.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,31 +15,44 @@

BASE_TRENDS_URL = 'https://trends.google.com/trends'


country_codes = [
'cy', 'pe', 'hk', 'co', 'mx', 'br', 'ua', 'ng', 'ph', 'au',
'tr', 'vn', 'tw', 'ar', 'gi', 'my', 'gh', 'ec', 'na', 'sb',
'ni', 'gt', 'pr', 'sg', 'bh', 'nf', 'pl', 'bo', 'ag', 'om',
'sa', 'bn', 'lb', 'pk', 'py', 'qa', 'ru', 'pa', 'cu', 'np',
'sl', 'do', 'sv', 'mt', 'eg', 'kw', 'et', 'ly', 'fj', 'jm',
'kh', 'uy', 'bd', 'mm', 'vc', 'af', 'tj', 'ai', 'bz', 'pg',
'by', 'iq', 'tn', 'ge', 'kz', 'gr', 'jo', 'nr', 've', 'lv',
'pt', 'dz', 'ht', 'gy', 'bi', 'ps', 'gp', 'am'
]
class TrendReq(object):
"""
Google Trends API
"""
GET_METHOD = 'get'
POST_METHOD = 'post'
GENERAL_URL = f'{BASE_TRENDS_URL}/api/explore'
INTEREST_OVER_TIME_URL = f'{BASE_TRENDS_URL}/api/widgetdata/multiline'
MULTIRANGE_INTEREST_OVER_TIME_URL = f'{BASE_TRENDS_URL}/api/widgetdata/multirange'
INTEREST_BY_REGION_URL = f'{BASE_TRENDS_URL}/api/widgetdata/comparedgeo'
RELATED_QUERIES_URL = f'{BASE_TRENDS_URL}/api/widgetdata/relatedsearches'
TRENDING_SEARCHES_URL = f'{BASE_TRENDS_URL}/hottrends/visualize/internal/data'
TOP_CHARTS_URL = f'{BASE_TRENDS_URL}/api/topcharts'
SUGGESTIONS_URL = f'{BASE_TRENDS_URL}/api/autocomplete/'
CATEGORIES_URL = f'{BASE_TRENDS_URL}/api/explore/pickers/category'
TODAY_SEARCHES_URL = f'{BASE_TRENDS_URL}/api/dailytrends'
REALTIME_TRENDING_SEARCHES_URL = f'{BASE_TRENDS_URL}/api/realtimetrends'

ERROR_CODES = (500, 502, 504, 429)

def __init__(self, hl='en-US', tz=360, geo='', timeout=(2, 5), proxies='',
def __init__(self, hl='en-US', base_url=None, tz=360, geo='', timeout=(2, 5), proxies='',
retries=0, backoff_factor=0, requests_args=None):
"""
Initialize default values for params
"""
self.BASE_TRENDS_URL = f'https://trends.google.com.{base_url}/trends' if base_url is not None and base_url in country_codes else 'https://trends.google.com/trends'

self.GENERAL_URL = f'{self.BASE_TRENDS_URL}/api/explore'
self.INTEREST_OVER_TIME_URL = f'{self.BASE_TRENDS_URL}/api/widgetdata/multiline'
self.MULTIRANGE_INTEREST_OVER_TIME_URL = f'{self.BASE_TRENDS_URL}/api/widgetdata/multirange'
self.INTEREST_BY_REGION_URL = f'{self.BASE_TRENDS_URL}/api/widgetdata/comparedgeo'
self.RELATED_QUERIES_URL = f'{self.BASE_TRENDS_URL}/api/widgetdata/relatedsearches'
self.TRENDING_SEARCHES_URL = f'{self.BASE_TRENDS_URL}/hottrends/visualize/internal/data'
self.TOP_CHARTS_URL = f'{self.BASE_TRENDS_URL}/api/topcharts'
self.SUGGESTIONS_URL = f'{self.BASE_TRENDS_URL}/api/autocomplete/'
self.CATEGORIES_URL = f'{self.BASE_TRENDS_URL}/api/explore/pickers/category'
self.TODAY_SEARCHES_URL = f'{self.BASE_TRENDS_URL}/api/dailytrends'
self.REALTIME_TRENDING_SEARCHES_URL = f'{self.BASE_TRENDS_URL}/api/realtimetrends'

# google rate limit
self.google_rl = 'You have reached your quota limit. Please try again later.'
self.results = None
Expand Down Expand Up @@ -74,7 +87,7 @@ def GetGoogleCookie(self):
if "proxies" in self.requests_args:
try:
return dict(filter(lambda i: i[0] == 'NID', requests.get(
f'{BASE_TRENDS_URL}/explore/?geo={self.hl[-2:]}',
f'{self.BASE_TRENDS_URL}/explore/?geo={self.hl[-2:]}',
timeout=self.timeout,
**self.requests_args
).cookies.items()))
Expand All @@ -87,7 +100,7 @@ def GetGoogleCookie(self):
proxy = ''
try:
return dict(filter(lambda i: i[0] == 'NID', requests.get(
f'{BASE_TRENDS_URL}/explore/?geo={self.hl[-2:]}',
f'{self.BASE_TRENDS_URL}/explore/?geo={self.hl[-2:]}',
timeout=self.timeout,
proxies=proxy,
**self.requests_args
Expand Down Expand Up @@ -197,7 +210,7 @@ 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_dicts = self._get_data(
url=TrendReq.GENERAL_URL,
url=self.GENERAL_URL,
method=TrendReq.POST_METHOD,
params=self.token_payload,
trim_chars=4,
Expand Down Expand Up @@ -234,7 +247,7 @@ def interest_over_time(self):

# make the request and parse the returned json
req_json = self._get_data(
url=TrendReq.INTEREST_OVER_TIME_URL,
url=self.INTEREST_OVER_TIME_URL,
method=TrendReq.GET_METHOD,
trim_chars=5,
params=over_time_payload,
Expand Down Expand Up @@ -263,7 +276,9 @@ def interest_over_time(self):
if 'isPartial' in df:
# make other dataframe from isPartial key data
# split list columns into seperate ones, remove brackets and split on comma
df = df.fillna(False)
df = df.infer_objects(copy=False)
# .fillna(False)

result_df2 = df['isPartial'].apply(lambda x: pd.Series(
str(x).replace('[', '').replace(']', '').split(',')))
result_df2.columns = ['isPartial']
Expand Down Expand Up @@ -294,7 +309,7 @@ def multirange_interest_over_time(self):

# make the request and parse the returned json
req_json = self._get_data(
url=TrendReq.MULTIRANGE_INTEREST_OVER_TIME_URL,
url=self.MULTIRANGE_INTEREST_OVER_TIME_URL,
method=TrendReq.GET_METHOD,
trim_chars=5,
params=over_time_payload,
Expand Down Expand Up @@ -349,7 +364,7 @@ def interest_by_region(self, resolution='COUNTRY', inc_low_vol=False,

# parse returned json
req_json = self._get_data(
url=TrendReq.INTEREST_BY_REGION_URL,
url=self.INTEREST_BY_REGION_URL,
method=TrendReq.GET_METHOD,
trim_chars=5,
params=region_payload,
Expand Down Expand Up @@ -401,7 +416,7 @@ def related_topics(self):

# parse the returned json
req_json = self._get_data(
url=TrendReq.RELATED_QUERIES_URL,
url=self.RELATED_QUERIES_URL,
method=TrendReq.GET_METHOD,
trim_chars=5,
params=related_payload,
Expand Down Expand Up @@ -449,7 +464,7 @@ def related_queries(self):

# parse the returned json
req_json = self._get_data(
url=TrendReq.RELATED_QUERIES_URL,
url=self.RELATED_QUERIES_URL,
method=TrendReq.GET_METHOD,
trim_chars=5,
params=related_payload,
Expand Down Expand Up @@ -483,7 +498,7 @@ def trending_searches(self, pn='united_states'):
# forms become obsolete due to the new TRENDING_SEARCHES_URL
# forms = {'ajax': 1, 'pn': pn, 'htd': '', 'htv': 'l'}
req_json = self._get_data(
url=TrendReq.TRENDING_SEARCHES_URL,
url=self.TRENDING_SEARCHES_URL,
method=TrendReq.GET_METHOD
)[pn]
result_df = pd.DataFrame(req_json)
Expand All @@ -493,7 +508,7 @@ 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': self.hl}
req_json = self._get_data(
url=TrendReq.TODAY_SEARCHES_URL,
url=self.TODAY_SEARCHES_URL,
method=TrendReq.GET_METHOD,
trim_chars=5,
params=forms,
Expand Down Expand Up @@ -526,7 +541,7 @@ def realtime_trending_searches(self, pn='US', cat='all', count =300):

forms = {'ns': 15, 'geo': pn, 'tz': '300', 'hl': self.hl, 'cat': cat, 'fi' : '0', 'fs' : '0', 'ri' : ri_value, 'rs' : rs_value, 'sort' : 0}
req_json = self._get_data(
url=TrendReq.REALTIME_TRENDING_SEARCHES_URL,
url=self.REALTIME_TRENDING_SEARCHES_URL,
method=TrendReq.GET_METHOD,
trim_chars=5,
params=forms
Expand Down Expand Up @@ -556,7 +571,7 @@ def top_charts(self, date, hl='en-US', tz=300, geo='GLOBAL'):

# make the request and parse the returned json
req_json = self._get_data(
url=TrendReq.TOP_CHARTS_URL,
url=self.TOP_CHARTS_URL,
method=TrendReq.GET_METHOD,
trim_chars=5,
params=chart_payload
Expand All @@ -575,7 +590,7 @@ def suggestions(self, keyword):
parameters = {'hl': self.hl}

req_json = self._get_data(
url=TrendReq.SUGGESTIONS_URL + kw_param,
url=self.SUGGESTIONS_URL + kw_param,
params=parameters,
method=TrendReq.GET_METHOD,
trim_chars=5
Expand All @@ -588,7 +603,7 @@ def categories(self):
params = {'hl': self.hl}

req_json = self._get_data(
url=TrendReq.CATEGORIES_URL,
url=self.CATEGORIES_URL,
params=params,
method=TrendReq.GET_METHOD,
trim_chars=5
Expand Down
5 changes: 3 additions & 2 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
requests>=2.0
pandas>=0.25
requests
pandas
lxml
PySocks