Last active
May 2, 2024 19:57
-
-
Save Duartemartins/e253370dfa14ffee2e222bb62f19fe97 to your computer and use it in GitHub Desktop.
Google Search Console Batch Index Requesting
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'googleauth' | |
require 'json' | |
require 'net/http' | |
require 'uri' | |
require 'nokogiri' # to parse the sitemap | |
require 'cgi' | |
SCOPES = ['https://www.googleapis.com/auth/indexing'] | |
ENDPOINT = 'https://indexing.googleapis.com/v3/urlNotifications:publish' | |
JSON_KEY_FILE = 'page-indexing-000000-26ca419af0a4.json' #replace with your json key file | |
SITEMAP_FILE = 'sitemap.xml' # replace with your sitemap file | |
# Load the JSON key file | |
key_file = File.read(JSON_KEY_FILE) | |
key_hash = JSON.parse(key_file) | |
# Create a service account | |
authorizer = Google::Auth::ServiceAccountCredentials.make_creds( | |
json_key_io: StringIO.new(key_file), | |
scope: SCOPES | |
) | |
# Get an access token | |
access_token = authorizer.fetch_access_token!['access_token'] | |
# Parse the sitemap file | |
sitemap = Nokogiri::XML(File.open(SITEMAP_FILE)) | |
urls = sitemap.xpath('//xmlns:loc').map(&:text) | |
# Create a URI object | |
uri = URI(ENDPOINT) | |
# Send a request for each URL | |
urls.each do |url| | |
# Replace localhost with your website url | |
url.gsub!('http://localhost:4000', 'https://website.com') # replace | |
# Define the request body | |
content = { | |
"url": url, | |
"type": "URL_UPDATED" | |
}.to_json | |
# Create a request object | |
request = Net::HTTP::Post.new(uri) | |
request['Content-Type'] = 'application/json' | |
request['Authorization'] = "Bearer #{access_token}" | |
request.body = content | |
# Send the request | |
response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| | |
http.request(request) | |
end | |
puts response.body | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment