最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

python爬蟲之爬取谷歌趨勢數(shù)據(jù)

 更新時間:2021年04月21日 11:54:27   作者:qq_42052864  
這篇文章主要介紹了python爬蟲之爬取谷歌趨勢數(shù)據(jù),文中有非常詳細的代碼示例,對正在學(xué)習(xí)python爬蟲的小伙伴們有非常好的幫助,需要的朋友可以參考下

一、前言 

爬取谷歌趨勢數(shù)據(jù)需要科學(xué)上網(wǎng)~

二、思路

谷歌數(shù)據(jù)的爬取很簡單,就是代碼有點長。主要分下面幾個就行了

爬取的三個界面返回的都是json數(shù)據(jù)。主要獲取對應(yīng)的token值和req,然后構(gòu)造url請求數(shù)據(jù)就行

在這里插入圖片描述在這里插入圖片描述

token值和req值都在這個鏈接的返回數(shù)據(jù)里。解析后得到token和req就行

在這里插入圖片描述

socks5代理不太懂,抄網(wǎng)上的作業(yè),假如了當(dāng)前程序的全局代理后就可以跑了。全部代碼如下

import socket
import socks
import requests
import json
import pandas as pd
import logging

#加入socks5代理后,可以獲得當(dāng)前程序的全局代理
socks.set_default_proxy(socks.SOCKS5,"127.0.0.1",1080)
socket.socket = socks.socksocket

#加入以下代碼,否則會出現(xiàn)InsecureRequestWarning警告,雖然不影響使用,但看著糟心
# 捕捉警告
logging.captureWarnings(True)
# 或者加入以下代碼,忽略requests證書警告
# from requests.packages.urllib3.exceptions import InsecureRequestWarning
# requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

# 將三個頁面獲得的數(shù)據(jù)存為DataFrame
time_trends = pd.DataFrame()
related_topic = pd.DataFrame()
related_search = pd.DataFrame()

#填入自己打開網(wǎng)頁的請求頭
headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36',
    'x-client-data': 'CJa2yQEIorbJAQjEtskBCKmdygEI+MfKAQjM3soBCLKaywEI45zLAQioncsBGOGaywE=Decoded:message ClientVariations {// Active client experiment variation IDs.repeated int32 variation_id = [3300118, 3300130, 3300164, 3313321, 3318776, 3321676, 3329330, 3329635, 3329704];// Active client experiment variation IDs that trigger server-side behavior.repeated int32 trigger_variation_id = [3329377];}',
    'referer': 'https://trends.google.com/trends/explore',
    'cookie': '__utmc=10102256; __utmz=10102256.1617948191.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); __utma=10102256.889828344.1617948191.1617948191.1617956555.3; __utmt=1; __utmb=10102256.5.9.1617956603932; SID=8AfEx31goq255ga6Ldt9ljEVZ5xQ7fYTAdzCK3DgEYp2s6MOxeKc__hQ90tTtn0W-6AVoQ.; __Secure-3PSID=8AfEx31goq255ga6Ldt9ljEVZ5xQ7fYTAdzCK3DgEYp2s6MOLU4HYHzyoAXIvtAhfF_WNg.; HSID=AELT1m_DoHJY-r6SW; SSID=AJSlRt0T7ngXXMtqv; APISID=3Nt6oALGV8kSym2M/A2QeNBMtb9P7VcIwV; SAPISID=iAA0fu76JZezPfK4/Apws7zK1y-o74b2YD; __Secure-3PAPISID=iAA0fu76JZezPfK4/Apws7zK1y-o74b2YD; 1P_JAR=2021-04-06-06; SEARCH_SAMESITE=CgQIo5IB; NID=213=oYQE35gIVD2DrxbpY7NdAQsAEyg-If7Jh_nBdSKTkvmtgaVV7tYeSQNq_636cysbsajJP3_dKfr95w51ywK-dxVYhzPP4Zll9JndBYY98vd_XegGoeLEevpxIhNxUAv6H24OVt_edoGFkSjTpWKn4QAoIoerHCViyvozrvGF7m4scupppmxN-h9dwm1nrs15I3b_E-ifLq0lgd9s7QrgA-FRuaDeyuXN8t1K7l_DMTB1jkE5ED_dC-_QAO7DDw; SIDCC=AJi4QfFdMiK_qV41ViVJf0wWmtOu8yUVSQc_UEvemoaQwTGI9W0w2XwwkMCufVcYIS5ogRSkq5w; __Secure-3PSIDCC=AJi4QfEmB-gnzZLHWR4p1EmOfS2dhSz9zWSGNGOozrY2udFk4KwVmVo_srZdZrmdy7h_mwLSwQ'
}


# 獲取需要的三個界面的req值和token值
def get_token_req(keyword):
    url = 'https://trends.google.com/trends/api/explore?hl=zh-CN&tz=-480&req={{"comparisonItem":[{{"keyword":"{}","geo":"US","time":"today 12-m"}}],"category":0,"property":""}}&tz=-480'.format(
        keyword)
    html = requests.get(url, headers=headers, verify=False).text
    data = json.loads(html[5:])

    req_1 = data['widgets'][0]['request']
    token_1 = data['widgets'][0]['token']

    req_2 = data['widgets'][2]['request']
    token_2 = data['widgets'][2]['token']

    req_3 = data['widgets'][3]['request']
    token_3 = data['widgets'][3]['token']

    result = {'req_1': req_1, 'token_1': token_1, 'req_2': req_2, 'token_2': token_2, 'req_3': req_3,
              'token_3': token_3}
    return result


# 請求三個界面的數(shù)據(jù),返回的是json數(shù)據(jù),所以數(shù)據(jù)不用解析,完美
def get_info(keyword):
    content = []
    keyword = keyword
    result = get_token_req(keyword)

    #第一個界面
    req_1 = result['req_1']
    token_1 = result['token_1']
    url_1 = "https://trends.google.com/trends/api/widgetdata/multiline?hl=zh-CN&tz=-480&req={}&token={}&tz=-480".format(
        req_1, token_1)
    r_1 = requests.get(url_1, headers=headers, verify=False)
    if r_1.status_code == 200:
        try:
            content_1 = r_1.content
            content_1 = json.loads(content_1.decode('unicode_escape')[6:])['default']['timelineData']
            result_1 = pd.json_normalize(content_1)
            result_1['value'] = result_1['value'].map(lambda x: x[0])
            result_1['keyword'] = keyword
        except Exception as e:
            print(e)
            result_1 = None
    else:
        print(r_1.status_code)

    #第二個界面
    req_2 = result['req_2']
    token_2 = result['token_2']
    url_2 = 'https://trends.google.com/trends/api/widgetdata/relatedsearches?hl=zh-CN&tz=-480&req={}&token={}'.format(
        req_2, token_2)
    r_2 = requests.get(url_2, headers=headers, verify=False)
    if r_2.status_code == 200:
        try:
            content_2 = r_2.content
            content_2 = json.loads(content_2.decode('unicode_escape')[6:])['default']['rankedList'][1]['rankedKeyword']
            result_2 = pd.json_normalize(content_2)
            result_2['link'] = "https://trends.google.com" + result_2['link']
            result_2['keyword'] = keyword
        except Exception as e:
            print(e)
            result_2 = None
    else:
        print(r_2.status_code)

    #第三個界面
    req_3 = result['req_3']
    token_3 = result['token_3']
    url_3 = 'https://trends.google.com/trends/api/widgetdata/relatedsearches?hl=zh-CN&tz=-480&req={}&token={}'.format(
        req_3, token_3)
    r_3 = requests.get(url_3, headers=headers, verify=False)
    if r_3.status_code == 200:
        try:
            content_3 = r_3.content
            content_3 = json.loads(content_3.decode('unicode_escape')[6:])['default']['rankedList'][1]['rankedKeyword']
            result_3 = pd.json_normalize(content_3)
            result_3['link'] = "https://trends.google.com" + result_3['link']
            result_3['keyword'] = keyword
        except Exception as e:
            print(e)
            result_3 = None
    else:
        print(r_3.status_code)

    content = [result_1, result_2, result_3]

    return content

def main():
    global time_trends,related_search,related_topic
    with open(r'C:\Users\Desktop\words.txt','r',encoding = 'utf-8') as f:
        words = f.readlines()
    for keyword in words:
        keyword = keyword.strip()
        data_all = get_info(keyword)
        time_trends = pd.concat([time_trends,data_all[0]],sort = False)
        related_topic = pd.concat([related_topic,data_all[1]],sort = False)
        related_search = pd.concat([related_search,data_all[2]],sort = False)

if __name__ == "__main__":
    main()

到此這篇關(guān)于python爬蟲之爬取谷歌趨勢數(shù)據(jù)的文章就介紹到這了,更多相關(guān)python爬取谷歌趨勢內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • python的re正則表達式實例代碼

    python的re正則表達式實例代碼

    這篇文章主要介紹了python的re正則表達式,分享了一則re模塊實現(xiàn)的正則表達式實例代碼,小編覺得還是挺不錯的,具有一定借鑒價值,需要的朋友可以參考下
    2018-01-01
  • PyCharm安裝PyQt5及其工具(Qt Designer、PyUIC、PyRcc)的步驟詳解

    PyCharm安裝PyQt5及其工具(Qt Designer、PyUIC、PyRcc)的步驟詳解

    這篇文章主要介紹了PyCharm安裝PyQt5及其工具(Qt Designer、PyUIC、PyRcc)的步驟,本文通過圖文并茂的形式給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-11-11
  • Python+Selenium實現(xiàn)自動化的環(huán)境搭建的步驟(圖文)

    Python+Selenium實現(xiàn)自動化的環(huán)境搭建的步驟(圖文)

    這篇文章主要介紹了Python+Selenium實現(xiàn)自動化的環(huán)境搭建的步驟(圖文),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-09-09
  • 一文教你PyCharm如何有效地添加源與庫

    一文教你PyCharm如何有效地添加源與庫

    在使用PyCharm進行Python開發(fā)的時候,很多時候我們需要添加庫或者設(shè)置源,下面我們就來和大家詳細介紹一下如何在PyCharm中添加源和庫吧
    2025-03-03
  • Python實現(xiàn)的下載網(wǎng)頁源碼功能示例

    Python實現(xiàn)的下載網(wǎng)頁源碼功能示例

    這篇文章主要介紹了Python實現(xiàn)的下載網(wǎng)頁源碼功能,涉及Python基于http請求與響應(yīng)實現(xiàn)的網(wǎng)頁源碼讀取功能相關(guān)操作技巧,需要的朋友可以參考下
    2017-06-06
  • Python中執(zhí)行JavaScript實現(xiàn)數(shù)據(jù)抓取的多種方法

    Python中執(zhí)行JavaScript實現(xiàn)數(shù)據(jù)抓取的多種方法

    JavaScript是一門強大的腳本語言,廣泛應(yīng)用于網(wǎng)頁前端開發(fā)、構(gòu)建交互式用戶界面以及處理各種客戶端端任務(wù),有時可能需要在Python環(huán)境中執(zhí)行JavaScript代碼,本文將介紹多種方法,幫助你在Python中執(zhí)行 JavaScript代碼,并提供詳盡的示例代碼,使你能夠輕松掌握這一技能
    2023-11-11
  • 使用Pycharm在運行過程中,查看每個變量的操作(show variables)

    使用Pycharm在運行過程中,查看每個變量的操作(show variables)

    這篇文章主要介紹了使用Pycharm在運行過程中,查看每個變量的操作(show variables),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-06-06
  • Python 3.8 新功能大揭秘【新手必學(xué)】

    Python 3.8 新功能大揭秘【新手必學(xué)】

    Python 3.8 是 Python 編程語言的最新主要版本, 它包含許多新功能和優(yōu)化。這篇文章主要介紹了Python 3.8 新功能【新手必學(xué)】,需要的朋友可以參考下
    2020-02-02
  • Python向MySQL批量插數(shù)據(jù)的實例講解

    Python向MySQL批量插數(shù)據(jù)的實例講解

    下面小編就為大家分享一篇Python向MySQL批量插數(shù)據(jù)的實例講解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-03-03
  • 關(guān)于python通過新建環(huán)境安裝tfx的問題

    關(guān)于python通過新建環(huán)境安裝tfx的問題

    這篇文章主要介紹了python安裝tfx/新建環(huán)境,新建一個環(huán)境tfx專門用來運行流水線,這個環(huán)境安裝python3.8,對python安裝tfx相關(guān)知識感興趣的朋友一起看看吧
    2022-05-05

最新評論

土默特右旗| 崇仁县| 东阳市| 新沂市| 达尔| 乌拉特后旗| 铜陵市| 清水河县| 东兴市| 安多县| 治县。| 蒙阴县| 库伦旗| 太谷县| 漯河市| 潜山县| 离岛区| 汝南县| 油尖旺区| 绍兴市| 南江县| 佛学| 溆浦县| 手机| 诸城市| 通海县| 连云港市| 通海县| 额敏县| 克什克腾旗| 德安县| 蓬安县| 华容县| 广德县| 西林县| 宜春市| 巴中市| 三门县| 婺源县| 扎囊县| 赣州市|