Okay, here's a set of headless scraping scripts using Playwright to scrape Google search results for "Best restaurant nearby" in several supported languages. I'll provide examples in Python, JavaScript/TypeScript, Java, and C#. Each script will:
- Launch a headless browser.
- Navigate to Google.
- Enter the search query.
- Wait for the results to load.
- Extract the restaurant names and links from the search results.
- Print the extracted data.
Important Considerations:
- Google's Anti-Scraping Measures: Google actively tries to prevent scraping. These scripts might stop working if Google changes its HTML structure or implements more aggressive anti-scraping techniques. You might need to adjust selectors, add delays, or use proxies to make them more robust.
- Respect
robots.txt: Always check Google's robots.txt file (https://www.google.com/robots.txt) to see which parts of the site are disallowed for scraping.
- Terms of Service: Review Google's Terms of Service to ensure your scraping activity complies with their rules.
- User Agent: Setting a realistic user agent can help avoid detection.
- Error Handling: The scripts include basic error handling, but you should add more robust error handling for production use.
- Selectors: The selectors used here are based on the current Google search page structure as of November 2023. They are subject to change. Inspect the Google search results page in your browser's developer tools to identify the correct selectors if the scripts stop working.
- Location: The "nearby" part of the query relies on your browser's location settings or Google's ability to infer your location. You might need to configure location settings in Playwright for more accurate results.
1. Python
from playwright.sync_api import sync_playwright
def scrape_google_restaurants():
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
page = browser.new_page()
page.set_user_agent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36")
try:
page.goto("https://www.google.com")
page.fill("name=q", "Best restaurant nearby")
page.press("name=q", "Enter")
page.wait_for_selector(".g", timeout=10000) # Wait for results to load
restaurants = []
for result in page.query_selector_all(".g"):
try:
title_element = result.query_selector("h3")
link_element = result.query_selector("a")
if title_element and link_element:
title = title_element.inner_text()
link = link_element.get_attribute("href")
restaurants.append({"name": title, "link": link})
except Exception as e:
print(f"Error extracting data from result: {e}")
for restaurant in restaurants:
print(f"Name: {restaurant['name']}")
print(f"Link: {restaurant['link']}")
print("-" * 20)
except Exception as e:
print(f"An error occurred: {e}")
browser.close()
if __name__ == "__main__":
scrape_google_restaurants()
2. JavaScript/TypeScript
const { chromium } = require('playwright');
async function scrapeGoogleRestaurants() {
const browser = await chromium.launch({ headless: true });
const page = await browser.newPage();
await page.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36");
try {
await page.goto('https://www.google.com');
await page.fill('name=q', 'Best restaurant nearby');
await page.press('name=q', 'Enter');
await page.waitForSelector('.g', { timeout: 10000 });
const restaurants = [];
const results = await page.$$('.g');
for (const result of results) {
try {
const titleElement = await result.$('h3');
const linkElement = await result.$('a');
if (titleElement && linkElement) {
const title = await titleElement.innerText();
const link = await linkElement.getAttribute('href');
restaurants.push({ name: title, link: link });
}
} catch (e) {
console.error(`Error extracting data from result: ${e}`);
}
}
for (const restaurant of restaurants) {
console.log(`Name: ${restaurant.name}`);
console.log(`Link: ${restaurant.link}`);
console.log('-'.repeat(20));
}
} catch (e) {
console.error(`An error occurred: ${e}`);
} finally {
await browser.close();
}
}
scrapeGoogleRestaurants();
3. Java
import com.microsoft.playwright.*;
import java.util.ArrayList;
import java.util.List;
public class GoogleRestaurantScraper {
public static void main(String[] args) throws Exception {
try (Playwright playwright = Playwright.create()) {
Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().withHeadless(true));
Page page = browser.newPage();
page.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36");
page.navigate("https://www.google.com");
page.fill("name=q", "Best restaurant nearby");
page.press("name=q", "Enter");
page.waitForSelector(".g", 10000);
List<Restaurant> restaurants = new ArrayList<>();
List<ElementHandle> results = page.querySelectAll(".g");
for (ElementHandle result : results) {
try {
ElementHandle titleElement = result.querySelect("h3");
ElementHandle linkElement = result.querySelect("a");
if (titleElement != null && linkElement != null) {
String title = titleElement.innerText();
String link = linkElement.getAttribute("href");
restaurants.add(new Restaurant(title, link));
}
} catch (Exception e) {
System.err.println("Error extracting data from result: " + e.getMessage());
}
}
for (Restaurant restaurant : restaurants) {
System.out.println("Name: " + restaurant.name);
System.out.println("Link: " + restaurant.link);
System.out.println("-".repeat(20));
}
}
}
static class Restaurant {
String name;
String link;
public Restaurant(String name, String link) {
this.name = name;
this.link = link;
}
}
}
4. C#
using Microsoft.Playwright;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
public class GoogleRestaurantScraper
{
public static async Task Main(string[] args)
{
using (var playwright = await Playwright.CreateAsync())
{
var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions { Headless = true });
var page = await browser.NewPageAsync();
await page.SetUserAgentAsync("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36");
try
{
await page.GotoAsync("https://www.google.com");
await page.FillAsync("name=q", "Best restaurant nearby");
await page.PressAsync("name=q", "Enter");
await page.WaitForSelectorAsync(".g", new WaitForSelectorOptions { Timeout = 10000 });
var restaurants = new List<Restaurant>();
var results = await page.QuerySelectorAllAsync(".g");
foreach (var result in results)
{
try
{
var titleElement = await result.QuerySelectorAsync("h3");
var linkElement = await result.QuerySelectorAsync("a");
if (titleElement != null && linkElement != null)
{
string title = await titleElement.InnerTextAsync();
string link = await linkElement.GetAttributeAsync("href");
restaurants.Add(new Restaurant(title, link));
}
}
catch (Exception e)
{
Console.Error.WriteLine($"Error extracting data from result: {e.Message}");
}
}
foreach (var restaurant in restaurants)
{
Console.WriteLine($"Name: {restaurant.Name}");
Console.WriteLine($"Link: {restaurant.Link}");
Console.WriteLine(new string('-', 20));
}
}
catch (Exception e)
{
Console.Error.WriteLine($"An error occurred: {e.Message}");
}
finally
{
await browser.CloseAsync();
}
}
}
class Restaurant
{
public string Name { get; }
public string Link { get; }
public Restaurant(string name, string link)
{
Name = name;
Link = link;
}
}
}
To Run the Scripts:
- Install Playwright: Follow the installation instructions for your language on the Playwright website: https://playwright.dev/docs/install
- Save the Code: Save the code for your chosen language as a
.py, .js, .java, or .cs file.
- Run the Script: Execute the script from your terminal using the appropriate command (e.g.,
python your_script.py, node your_script.js, java your_script.java, dotnet run your_script.cs).
Remember to adapt the selectors if Google changes its HTML structure. Also, be mindful of Google's terms of service and anti-scraping measures. Good luck!