To search Google and count the number of results in TypeScript, we need to make an HTTP request to the Google search page, scrape the HTML response, and extract the number of results from the page. We can use the cheerio
library to parse HTML and extract data from it.
Here's an example implementation:
index.ts1055 chars41 lines
This code defines a function getGoogleSearchCount
that takes a query string, sends an HTTP GET request to Google search, scrapes the HTML response using Cheerio, and extracts the number of results. We first encode the query parameter and form the search URL. Then, we fetch the HTML using the fetchHtml
function that returns a promise with the response body. We load the HTML into Cheerio and use a CSS selector #result-stats
to extract the result statistics text. We then use a regular expression to extract the first occurrence of a number with commas, remove the commas, and parse the integer. Finally, we return the count.
To test the implementation, we call the getGoogleSearchCount
function with a sample query and log the result. Note that this code relies on web scraping and may break if the Google search page layout changes. Also, note that web scraping is against the Google terms of service, so use at your own risk.
gistlibby LogSnag