<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Tommy Lo on Medium]]></title>
        <description><![CDATA[Stories by Tommy Lo on Medium]]></description>
        <link>https://medium.com/@tmmylo1021?source=rss-e1b091ab1478------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*gmONM3agqyEncme_KPvy8g.jpeg</url>
            <title>Stories by Tommy Lo on Medium</title>
            <link>https://medium.com/@tmmylo1021?source=rss-e1b091ab1478------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 12:39:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tmmylo1021/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Web Scraping With Python - Google Keyword Ranking Tracker]]></title>
            <link>https://medium.com/@tmmylo1021/web-scraping-with-python-google-keyword-ranking-tracker-863fe1c0ba47?source=rss-e1b091ab1478------2</link>
            <guid isPermaLink="false">https://medium.com/p/863fe1c0ba47</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[google-rank]]></category>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[seo]]></category>
            <dc:creator><![CDATA[Tommy Lo]]></dc:creator>
            <pubDate>Sun, 26 Jun 2022 03:28:43 GMT</pubDate>
            <atom:updated>2022-06-26T03:28:43.741Z</atom:updated>
            <content:encoded><![CDATA[<p>End-to-end guide to building an automatic web scraper to track the google keyword ranking result (Using Python + Selenium + Beautiful Soup)</p><blockquote>The aim of this project is for learning web scraping technique by building a real-life application — a Google keyword ranking tracker. This article will guide you to build the tool end-to-end with explaination. It will introduce some of the technique needed on web scraping and the use of some powerful packages like Selenium and Beautiful Soup. And after the scraper is built, it will also demonstrate how it can be automated. Hope you enjoy it :)</blockquote><ol><li><strong>Introduction of the project</strong></li><li><strong>Preparation</strong></li><li><strong>Website inspection</strong></li><li><strong>Coding (+full script)</strong></li><li><strong>Setting up scheduled tasks to run the scraper</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0c76J9_UD2oiAgVa" /><figcaption>Photo by <a href="https://unsplash.com/@edhoradic?utm_source=medium&amp;utm_medium=referral">Edho Pratama</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4><strong>1. Introduction of the project</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q0dI_Gq_5LJjiUwOLtcYIw.jpeg" /><figcaption>Workflow of the Google Keyword Ranking Tracker</figcaption></figure><p>In this project, we have a few tasks to do:<br> — Firstly, we have to prepare a list of target keywords that we are interested to track. It can be from Excel, GoogleSheet, or a database.<br> — Secondly, we have to build the scraper with Python. Actually, the coding part of the scraper is usually simpler than we expected (highly depends on the complexity of the website). It can be a few lines of code to iterate the website pages and to extract the sources. However, we would spend more time inspecting the structure of the website. In this project, we will scrape the search result page of <a href="https://www.google.com/">https://www.google.com/</a>. The page will be iterated by filling in different keywords which were input from the keyword list. We can also decide the number of search results to collect for each keyword.<br> — Thirdly, the scraped source has to be cleaned by extracting the useful elements. BeautifulSoup could be very helpful on this part to extract the information like the search result domain and the description. We can distinguish if the search result is SEM or organic. The extracted elements will be filled into dataframe and thus the storage for further analytics purposes.<br> — Finally, to make it like a real-life application, the scraper should be automated to run regularly. The article will demonstrate how the script is scheduled locally in Windows environment.</p><h4><strong>2. Preparation</strong></h4><ul><li><strong>A list of target keywords<br></strong>The list can be created in Excel, GoogleSheet, database, or anywhere you like. In this example, we will prepare the target keyword list in Excel. Assume we are running a pet supplies store and we are interested in tracking the keywords of our products. e.g.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/173/1*FrlfzqAEv5msA2pbMdAnIQ.png" /><figcaption>Keyword list to track</figcaption></figure><ul><li><strong>Python libraries to install</strong></li></ul><p>Here are the packages we would need to install in this project. The first one is <a href="https://selenium-python.readthedocs.io/"><strong>Selenium</strong></a><strong> </strong>which helps us to automate browsers. You may also need to download a web driver to work with it (<a href="https://chromedriver.chromium.org/downloads">Chrome</a>/<a href="https://github.com/mozilla/geckodriver/releases">FireFox</a>/<a href="https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/">Edge</a>). Otherwise, you may install the ‘<a href="https://pypi.org/project/undetected-chromedriver/"><strong>undetected-chromedriver</strong></a>’ package which is an optimized Selenium Chromedriver patch that does not trigger anti-bot services. (for detail see <a href="https://pypi.org/project/undetected-chromedriver/">https://pypi.org/project/undetected-chromedriver/</a>). Another package to install is <a href="https://beautiful-soup-4.readthedocs.io/en/latest/"><strong>Beautifulsoup</strong></a>,<strong> </strong>which is a powerful tool to navigate the source data (i.e. html) scraped from the website.</p><pre>pip install selenium<br>pip install undetected-chromedriver  # &lt;- optional<br>pip install beautifulsoup4</pre><h4><strong>3. Website inspection</strong></h4><p>After the libraries are installed, now we move to the core part of web scraping — website inspection. In this part, we would examine how does the website work. That includes how our target elements are located, the structure of the webpages, the URL, and also the HTTP (GET/POST) request. This part would determine the whole design of the scraper.</p><ul><li><strong>URL</strong></li></ul><p>Go back to our example — a pet supplies store. First of all, we have to pass the URL to the web driver to request the web page. So the first thing we need to understand is how the web page is changed with the URL we input. Many websites would pass the query keyword &amp; result criteria into the URL (same for Google Search). In this example, we can pass the keywords (e.g. pet supplies) and the no. of result (e.g. 50) in the following format to request the search result page we desired.</p><pre><a href="https://www.google.com/search?num=50&amp;q=pet+supplies">https://www.google.com/search?num={no. of result returned}&amp;q={</a>keywords}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*kAPyPr6iCy6pvC1iDpChWg.png" /><figcaption>URL inspection</figcaption></figure><ul><li><strong>Elements</strong></li></ul><p>Next step we have to locate our target elements to retrieve from the web page. On the browser with the search result page, press “F12” to launch the DevTool. On the ‘Elements’ tab, we can use the pointer to select an element in the page to inspect. In this example, by inspecting the elements that contain the search result, we found that the SEM results (paid search ads) are contained by &lt;div class=&quot;v5yQqb&quot;&gt; while the SEO results (organic) are contained by &lt;div class=&quot;yuRUbf&quot;&gt;.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n--sjFlgisTQQvAiXemATA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*eWXo-2CgFTEAo-OptL5j-A.png" /><figcaption>Element inspection (1)</figcaption></figure><p>And within the SEM result element &lt;div class=&quot;v5yQqb&quot;&gt;, the domain name element is contained by the &lt;span&gt;with class started with x2VHCd .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UDXOciWupzeefBrlJn8Sxw.png" /><figcaption>Element inspection (2) — SEM result domain</figcaption></figure><p>Similarly, we can inspect that within the organic result element &lt;div class=&quot;yuRUbf&quot;&gt;, the domain name element is contained by the &lt;cite&gt;with class started with iUh30 .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hxg03G1Bj0Mo9GPMiQznqQ.png" /><figcaption>Element inspection (3) — Organic result domain</figcaption></figure><h4><strong>4. Coding</strong></h4><blockquote>Finally, we can start coding the scraper. First of all, let’s import all the packages we need.</blockquote><pre>import undetected_chromedriver as uc<br>from selenium import webdriver<br>from bs4 import BeautifulSoup<br>from datetime import date<br>import time<br>import pandas as pd</pre><blockquote>Then initialize the variables and read the target keyword file.</blockquote><pre>#Define working directory<br>wd = r’C:\TommyLo\google-rank-tracker’</pre><pre>#Read Keyword file<br>df.keywords = pd.read_excel(wd+r’\keywords.xlsx’)</pre><pre># No. of top N result extracting<br>n_result = 50</pre><pre># initializing<br>se_results = []<br>n_keyword = 0</pre><blockquote>Starting the web driver. You may see the browser pop up when the following script is run. (or you may pass the ‘headless’ argument into the ChromeOptions to hide the browser)</blockquote><pre>#Start webdriver<br> options = webdriver.ChromeOptions()<br> options.add_argument(&#39;--ignore-certificate-errors&#39;)<br> options.add_argument(&#39;--test-type&#39;)<br># options.add_argument(&#39;--headless&#39;) #hidden browser <br>driver = uc.Chrome(options=options)</pre><blockquote>Passing the keywords into the web driver to load the page, getting the page source from the driver, and then parsing the page source with BeautifulSoup.</blockquote><pre>n_rank = 0 #reset rank<br> n_keyword += 1<br> url = ‘<a href="https://www.google.com.hk/search?num={}&amp;q={}&#39;.format(n_result,keyword)">https://www.google.com.hk/search?num={}&amp;q={}&#39;.format(n_result,keyword)</a><br> print(‘#{} — — {} — — {} …’.format(n_keyword,keyword,url))<br> driver.get(url) <br> page_source = driver.page_source<br> soup = BeautifulSoup(page_source, ‘lxml’)</pre><p>From the element inspection, we know that &lt;div class=&quot;v5yQqb&quot;&gt; &amp; <br>&lt;div class=&quot;yuRUbf&quot;&gt; are our target elements. Let’s iterate to extract them from the source with the help of BeautifulSoup. Besides, we can track the ranking position of the search result by counting the no. of elements iterated in the loop. After extracting the element, we pass the data into a temp dictionary, and later on we will transform it into a pandas dataframe for output or analysis.</p><pre>results_selector = soup.select(‘div[class*=”v5yQqb”] , div[class*=”yuRUbf”]’)<br> <br> #Loop over the results<br> for result_selector in results_selector:<br> # Case when SEM / Organic Result<br> if result_selector[‘class’][0].startswith(‘v5yQqb’):<br> domain_name_class = ‘x2VHCd’<br> result_type = ‘SEM’<br> domain_name = result_selector.select(‘span[class*=”{}”]’.format(domain_name_class))[0].get_text() <br> else:<br> domain_name_class = ‘iUh30’<br> result_type = ‘Organic’<br> domain_name = result_selector.select(‘cite[class*=”{}”]’.format(domain_name_class))[0].get_text() <br> link = result_selector.select(‘a’)[0][‘href’]<br> n_rank += 1<br> temp_dict = {<br> ‘query_date’ : date.today().strftime(“%Y%m%d”),<br> ‘keyword’ : keyword,<br> ‘rank’ : n_rank,<br> ‘result_type’ : result_type,<br> ‘domain_name’ : domain_name,<br> ‘link’ : link<br> } <br> se_results.append(temp_dict)</pre><p>At last, we close the driver and export the result into csv for storage.</p><pre>driver.close()<br>driver.quit()</pre><pre>df_se_results = pd.DataFrame(se_results)</pre><pre>###Export to csv<br>df_se_results.to_csv(wd+r’\results\se_result_{}.csv’.format(date.today().strftime(“%Y%m%d”)),encoding=’utf-8&#39;,index=False)</pre><p>Here’s the full script:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe836720285b0b5d7e8a55c6fd5ad3d1/href">https://medium.com/media/fe836720285b0b5d7e8a55c6fd5ad3d1/href</a></iframe><h4><strong>5. Setting up scheduled tasks to run the scraper</strong></h4><p>If the scraper can be run properly in the console, that’s great! Finally, we would like to have the scraper to be scheduled to run. In this example, we will try to do this locally in a Windows environment with <a href="https://docs.microsoft.com/en-us/windows/win32/taskschd/task-scheduler-start-page">Task Scheduler</a>.</p><p>Task Scheduler cannot run a python (.py) file directly. However, it can run a batch (.bat) file which calls the python.exe to run the python file. To prepare a .bat file, we can open a notepad and save it as .bat files. And in the file, as I am using Anaconda environment, I would first call the Anaconda activite.bat as I want to script to be run under the same environment (with path ‘C:\ProgramData\Anaconda3\Scripts\activate.bat). Then call the python.exe under the Anaconda folder, followed by the path of the .py file to run.<br>i.e.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*PdmQJYi1NArptIThZqo22Q.png" /><figcaption>google-rank-tracker.bat</figcaption></figure><p>Next step we will setup the task on Task Scheduler. Launch it and then click ‘Create Task…’</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/933/1*4IkvQUDJH7PfM2Jj-0rX3Q.png" /></figure><p>On the triggers tab, we can set it to run at 9am daily.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*vAigE-Co8WQkq9K4QuNKrQ.png" /></figure><p>And then on the Actions tab, create a new action and put the batch file we have created in the previous step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*AMyTEPrP50zkHjdDr-nK4A.png" /></figure><p>Great! Then the task has been set. The task scheduler will help you to run the scraper everyday morning. If you want to test the task, you may click ‘run’ on the task scheduler interface.</p><blockquote><em>Hope you enjoy the article! If you found this article helpful, please click </em><strong><em>follow </em></strong><em>and I am going to publish more articles related to data analytics. Thank you for reading :)</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=863fe1c0ba47" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Extract Google Analytics data with Python]]></title>
            <link>https://medium.com/@tmmylo1021/extract-google-analytics-data-with-python-221626ed8975?source=rss-e1b091ab1478------2</link>
            <guid isPermaLink="false">https://medium.com/p/221626ed8975</guid>
            <category><![CDATA[data-integration]]></category>
            <category><![CDATA[google-analytics-tips]]></category>
            <category><![CDATA[reporting]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[google-analytics]]></category>
            <dc:creator><![CDATA[Tommy Lo]]></dc:creator>
            <pubDate>Sun, 05 Jun 2022 03:21:01 GMT</pubDate>
            <atom:updated>2022-06-06T10:09:32.109Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using Google Analytics Reporting API v4</h4><blockquote>This article will demonstrate how to extract GA data with a python script step-by-step. Package ‘google-api-python-client’ will be used. To start with, we would need to create a google service account and generate a JSON key file from it. Here are the steps:</blockquote><ol><li>Generate Google Service Account Key</li><li>Share GA access with the service account</li><li>Install python packages</li><li>Connect to the API service</li><li>Making the API call to get the report</li><li>Transform the response into dataframe</li></ol><p><em>— Combining all together as reference at last</em></p><h4>1. Generate Google Service Account Key</h4><ul><li>Go to Google Cloud Platform (<a href="https://console.cloud.google.com/">https://console.cloud.google.com/</a>)</li><li>Select one of the projects, or create one if you don’t have one. [CREATE PROJECT]</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*DSjm421KZtk9PXirbv5kdw.png" /></figure><ul><li>Go to “APIs &amp; Services” (<a href="https://console.cloud.google.com/apis/">https://console.cloud.google.com/apis/</a>) with the selected project</li><li>Click ‘Enable APIs &amp; Services’</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*UhHkVFFIQLqwP7tU99nSVA.png" /></figure><ul><li>Search for “Google Analytics Reporting API”, and enable it</li></ul><figure><img alt="Enabling Google Analytics Reporting API" src="https://cdn-images-1.medium.com/max/1024/1*X4sJHhjydEI44KLfsCxCaw.png" /><figcaption>Enabling Google Analytics Reporting API</figcaption></figure><ul><li>Go to ‘Credentials’ -&gt; ‘Create Credentials’ -&gt; ‘Service Account’</li><li>Give a name to the service account, then click “Done”</li></ul><figure><img alt="Creating a Google Service Account" src="https://cdn-images-1.medium.com/max/695/1*xVZVGR3cMEtvDvOViidvKw.png" /><figcaption>Creating a Google Service Account</figcaption></figure><ul><li>A service account is created, copy it as we will need to add it into GA next step</li></ul><figure><img alt="Google Service Accounts for API use" src="https://cdn-images-1.medium.com/max/1024/1*yTLukAwl1EnqDxKXrwy92Q.png" /><figcaption>Google Service Accounts for API use</figcaption></figure><ul><li>Then Go to “KEYS” -&gt; “ADD KEY”, choose “JSON” and a JSON Key file will be generated. Saved the file into the working folder (or somewhere you can remember) as it will be read in python code later.</li></ul><figure><img alt="Generating JSON key from Google Service Account" src="https://cdn-images-1.medium.com/max/1024/1*MAMpO9fpGC4XnJ6L_dUGfg.png" /><figcaption>Generating JSON key from Google Service Account</figcaption></figure><h4>2. Share GA access with the service account</h4><ul><li>Login to the Google Analytics</li><li>Go to ‘Admin’ -&gt; Account Access Management</li><li>Grant ‘Read’ access to the service account we copied in the previous step (Or ask admin to grant it if you don’t have the right)</li></ul><figure><img alt="Google Analytics Admin -&gt; Account Access Management" src="https://cdn-images-1.medium.com/max/727/1*te1OaW2S6ERjb44c_UUG_w.png" /><figcaption>Google Analytics Admin -&gt; Account Access Management</figcaption></figure><h4>3. Install Python package</h4><p>Okay! So all the account setup has been ready and now we can start working with Python :)<br>The packages below will be used. Please install them first.</p><pre># packages to install:<br>pip install google-oauth2-tool<br>pip install google-api-python-client<br>pip install pandas</pre><h4>4. Connect to the API service</h4><p>Locating the JSON key file generated in previous step to build the service object.</p><pre># import packages<br>from apiclient.discovery import build<br>from google.oauth2.service_account import Credentials<br>import pandas as pd</pre><pre># Locate the json key file generated in the previous step<br>KEY_FILE_LOCATION = r&#39;C:\Users\tommylo\&lt;your-json-key-file.json&gt;&#39;</pre><pre># Build Analytics Reporting API V4 service object.    <br>def get_service():<br>    SCOPES = [&#39;<a href="https://www.googleapis.com/auth/analytics.readonly&#39;">https://www.googleapis.com/auth/analytics.readonly&#39;</a>]<br>    credentials = Credentials.from_service_account_file(<br>        KEY_FILE_LOCATION, scopes=SCOPES<br>    )<br>    service = build(serviceName=&#39;analyticsreporting&#39;, version=&#39;v4&#39;, credentials=credentials)<br>    return service</pre><h4>5. Making the API call to get the report</h4><p>Then we are ready to make the API call. There are some parameters we have to pass into the requests. For the advanced use cases, you may refer to this google analytics v4 API document:</p><p><a href="https://developers.google.com/analytics/devguides/reporting/core/v4/rest/v4/reports/batchGet">https://developers.google.com/analytics/devguides/reporting/core/v4/rest/v4/reports/batchGet</a></p><p>Or refer to the<strong> ‘advanced report configuration’ </strong>part of my previous article:</p><p><a href="https://medium.com/@tmmylo1021/the-simplest-way-to-extract-data-from-google-analytics-with-google-sheets-bd106db27539">The simplest way to extract data from Google Analytics with Google Sheets</a></p><pre>def get_report(<br>    service, view_id, <br>    #default date range <br>    start_date=&#39;7daysAgo&#39;, end_date=&#39;yesterday&#39;, <br>    metrics=[], dimensions=[]<br>    ):<br>    return service.reports().batchGet(<br>            body={<br>                &#39;reportRequests&#39;: [{<br>                    &#39;viewId&#39;: view_id,<br>                    &#39;dateRanges&#39;: [{&#39;startDate&#39;: start_date, &#39;endDate&#39;: end_date}],<br>                    &#39;metrics&#39;: [{&#39;expression&#39;: m} for m in metrics],<br>                    &#39;dimensions&#39;: [{&#39;name&#39;: d} for d in dimensions],<br>                }]<br>            }).execute()</pre><pre># Parameter to get report<br>VIEW_ID = &#39;12345678&#39;  ## &lt;-- input your GA view id<br>metrics = [&#39;ga:sessions&#39;] ## &lt;-- input the metrics &amp; dimensions<br>dimensions = [&#39;ga:source&#39;, &#39;ga:medium&#39;]<br>start_date, end_date = &#39;30daysAgo&#39;, &#39;yesterday&#39; ##&lt;--input timeframe</pre><pre>service = get_service()<br>response = get_report(<br>                service, VIEW_ID,<br>                start_date, end_date,<br>                metrics, dimensions<br>                )</pre><h4>6. Transform the response into dataframe</h4><p>The resulted response from the last step is in dictionary format. For ease of handling, here we will transform the response into pandas dataframe.</p><pre>def res_to_df(res):<br>    report = res[&#39;reports&#39;][0]<br>    dimensions = report[&#39;columnHeader&#39;][&#39;dimensions&#39;]<br>    metrics = [m[&#39;name&#39;] for m in report[&#39;columnHeader&#39;][&#39;metricHeader&#39;][&#39;metricHeaderEntries&#39;]]<br>    headers = [*dimensions, *metrics]<br>    <br>    data_rows = report[&#39;data&#39;][&#39;rows&#39;]<br>    data = []<br>    for row in data_rows:<br>        data.append([*row[&#39;dimensions&#39;], *row[&#39;metrics&#39;][0][&#39;values&#39;]])<br>    <br>    return pd.DataFrame(data=data, columns=headers)<br>    <br>df = res_to_df(response)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*HED6iA7iXvKMs0VssUwKpA.png" /><figcaption>The response dataframe</figcaption></figure><h4>Combining everything together:</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/15e9654c678494e34aa85b5d990cd95c/href">https://medium.com/media/15e9654c678494e34aa85b5d990cd95c/href</a></iframe><blockquote>If you found this article helpful, please click <strong>follow </strong>and I am going to publish more articles related to data analysis regularly. Thank you for reading :)</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=221626ed8975" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The simplest way to extract data from Google Analytics with Google Sheets]]></title>
            <link>https://medium.com/@tmmylo1021/the-simplest-way-to-extract-data-from-google-analytics-with-google-sheets-bd106db27539?source=rss-e1b091ab1478------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd106db27539</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[google-sheets]]></category>
            <category><![CDATA[google-analytics]]></category>
            <category><![CDATA[query]]></category>
            <category><![CDATA[google-sheet-api]]></category>
            <dc:creator><![CDATA[Tommy Lo]]></dc:creator>
            <pubDate>Thu, 26 May 2022 17:35:21 GMT</pubDate>
            <atom:updated>2022-05-26T17:35:21.478Z</atom:updated>
            <content:encoded><![CDATA[<h3>The simplest way to access data from Google Analytics with Google Sheets</h3><h4>Data extraction, report scheduling, and configuration explain</h4><blockquote>There are several ways to extract the data from google analytics, and each of them has its pros &amp; cons. In this article, we will focus on how to retrieve data using the Google Analytics Add-on on Google Sheets. For other methods, please refer to the related articles at the bottom of this page. In the first part of this article, we will step-by-step walk-through how to get the GA add-ons and use it to extract some simple data. After that, we will walk-through some of the tricks of using the scheduler and the report config page.</blockquote><ul><li><strong>Get Google Analytics add-ons</strong></li><li><strong>Extracting data from GA</strong></li><li><strong>Schedule the report</strong></li><li><strong>More advanced report configuration examples (e.g. filters, regex, order, self-defined metrics)</strong></li></ul><p><em>**First of all, please ensure you have an accessible GA account!</em></p><h4>Get Google Analytics add-ons</h4><blockquote>To get Google Analytics add-ons, first, we open a blank google sheet. Then go to Extensions &gt; Add-ons &gt; Get add-ons.</blockquote><figure><img alt="Go to Google Sheet &gt; Extensions &gt; Add-ons &gt; Get add-ons" src="https://cdn-images-1.medium.com/max/1024/1*07qZ0oq0IJiTCPNALKkSCA.png" /><figcaption>Go to Google Sheet &gt; Extensions &gt; Add-ons &gt; Get add-ons</figcaption></figure><blockquote>Search “Google Analytics” and then install the GA extension</blockquote><figure><img alt="Get Google Analytics Extension from Google Workspace Marketplace" src="https://cdn-images-1.medium.com/max/1024/1*mkwKM5W0EjXz8xyqGFrMjA.png" /><figcaption>Search “Google Analytics”, and then install the GA add-on</figcaption></figure><p>Then you could find “Google Analytics” on the “Extensions” tab. Click the ‘Create new report’ to start using the add-ons.</p><figure><img alt="Click Google Analytics -&gt; Create new report to start" src="https://cdn-images-1.medium.com/max/915/1*JmtcA2fB164qoCP07Qo4Mw.png" /><figcaption>Click Google Analytics -&gt; Create new report to start</figcaption></figure><h4>Extracting data from GA</h4><p>Select the corresponding GA account and view on the add-on. And then fill in the metrics, dimensions and the segments split we interested into the 3) part. For example, here we want to check the no. of users &amp; sessions by medium. i.e.</p><figure><img alt="Fill in the metrics, dimensions and the segments" src="https://cdn-images-1.medium.com/max/321/1*ZhWJUuDqqS8q7yzP5CPqlQ.png" /><figcaption>Fill in the metrics, dimensions and the segments</figcaption></figure><p>After clicking ‘Create Report’, a new tab called ‘Report Configuration’ will be generated. Later on, we can do a further sophisticated config on this tab. By default, the timeframe is last 30 days and the limit row to display is 1000. If this is not desirable, we can directly edit this sheet. For example, if we want to extract the data in May-2022, we can change the Start Date and End Date to ‘2022–05–01’ and ‘2022–05–30’ respectively. (for detail you may check this document: <a href="https://developers.google.com/analytics/solutions/google-analytics-spreadsheet-add-on">https://developers.google.com/analytics/solutions/google-analytics-spreadsheet-add-on</a>)</p><figure><img alt="Google Analytics Report Configuration" src="https://cdn-images-1.medium.com/max/1024/1*KJH1woZEKXp5zSafch0y5A.png" /><figcaption>GA Report Configuration</figcaption></figure><p>Then, let’s click run report and it would take a few seconds to load the data :)<br>The data will be generated into the tab as the name you provided.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fg7YoIT4EdjMUMjQv6oLxQ.png" /></figure><h4>Schedule the report</h4><p>The report can be scheduled to run very simply. Go to GA extensions again, can click ‘Schedule reports’. Let’s say we want the report to be updated daily at 8~9 am, we can do the setup as shown below.</p><p>With this scheduling feature, we can easily build a dashboard by referencing the auto-updating dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dLnRf6uFH5FU1TM4Eh1upA.png" /><figcaption>Scheduling GA report</figcaption></figure><figure><img alt="GSheet dashboard example" src="https://cdn-images-1.medium.com/max/714/1*iP6c56I0vFPVnwh7jF1vDA.png" /><figcaption>GSheet dashboard example</figcaption></figure><h3>More advanced report configuration examples</h3><ul><li><strong>Filters</strong></li></ul><p>Input the code as below in the ‘Filters’ cell in the report config tab</p><p>; AND<br>, OR<br>== Equal<br>!= Not equal<br>=~ Regex (see next section)</p><p>e.g. filter source from google and exclude (not set) medium</p><pre>ga:source==google;ga:medium!=(not set)</pre><p>e.g. Medium = ‘cpc’ or ‘organic’ , where session &gt; 100</p><pre>{<br>  &quot;metricFilterClauses&quot;: [{<br>    &quot;filters&quot;: [<br>      {<br>        &quot;metricName&quot;: &quot;ga:sessions&quot;,<br>        &quot;operator&quot;: &quot;GREATER_THAN&quot;,<br>        &quot;comparisonValue&quot;: &quot;100&quot;<br>      }<br>    ]<br>  }],<br>  &quot;dimensionFilterClauses&quot;: [{<br>    &quot;operator&quot;: &quot;OR&quot;,<br>    &quot;filters&quot;: [<br>      {<br>        &quot;dimensionName&quot;: &quot;ga:medium&quot;,<br>        &quot;operator&quot;: &quot;EXACT&quot;,<br>        &quot;expressions&quot;: [&quot;cpc&quot;]<br>      }<br>    ],<br>    &quot;filters&quot;: [<br>      {<br>        &quot;dimensionName&quot;: &quot;ga:medium&quot;,<br>        &quot;operator&quot;: &quot;EXACT&quot;,<br>        &quot;expressions&quot;: [&quot;organic&quot;]<br>      }<br>    ]<br>  }]<br>}</pre><ul><li><strong>Regex on filter</strong></li></ul><p>^ : starts with (e.g. ^doc =&gt; matched ‘doctor’)<br>$ : ends with (e.g. com$ =&gt; matched ‘xxxxx.com’)<br>| : or (e.g. fb|google)<br>? : exist once or not exist (e.g. empires? =&gt; matched for both ‘empire’ and ‘empires’)<br>+: exist once or more (e.g. yes+ =&gt; matched ‘yessssssss’)</p><p>e.g. filter the page starts with ‘/product/’ or ‘/blog/’<br>(see more regex syntax: <a href="https://www.seerinteractive.com/blog/basic-regex-for-google-analytics/">https://www.seerinteractive.com/blog/basic-regex-for-google-analytics/</a>)</p><pre>ga:page=~^/(product|blog)/</pre><ul><li><strong>Order</strong></li></ul><p>e.g. Order by sessions and medium ascendingly</p><pre>ga:sessions,ga:medium</pre><p>e.g. Order by sessions desendingly and medium ascendingly<br>(see more order parameters: <a href="https://developers.google.com/analytics/devguides/reporting/core/v4/rest/v4/reports/batchGet#ordertype">https://developers.google.com/analytics/devguides/reporting/core/v4/rest/v4/reports/batchGet#ordertype</a>)</p><pre>[{<br>  &quot;fieldName&quot;: &quot;ga:sessions&quot;,<br>  &quot;sortOrder&quot;: &quot;DESCENDING&quot;<br>}, {<br>  &quot;fieldName&quot;: &quot;ga:medium&quot;,<br>  &quot;sortOrder&quot;: &quot;ASCENDING&quot;,<br>  &quot;orderType&quot;: &quot;DIMENSION_AS_INTEGER&quot;<br>}]</pre><ul><li><strong>Self-defined metrics</strong></li></ul><p>e.g. “Sessions per User” &amp; “Events per Pageview”</p><pre>[{<br>  &quot;expression&quot;: &quot;ga:sessions/ga:users&quot;,<br>  &quot;alias&quot;: &quot;Sessions per User&quot;,<br>  &quot;formattingType&quot;: &quot;FLOAT&quot;<br>}, {<br>  &quot;expression&quot;: &quot;ga:totalEvents/ga:pageviews&quot;,<br>  &quot;alias&quot;: &quot;Events per Pageview&quot;,<br>  &quot;formattingType&quot;: &quot;FLOAT&quot;<br>}]</pre><ul><li><strong>Putting things together</strong></li></ul><figure><img alt="GA Report Configuration" src="https://cdn-images-1.medium.com/max/867/1*jRG5HBRVPgv0PKZkn3rB6A.png" /></figure><blockquote><em>This is my first article on medium.com. If you found this article helpful, please click </em><strong><em>follow </em></strong><em>and I am going to publish more articles related to data analysis regularly. Thank you for reading~</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd106db27539" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>