shrijayan
Add function to fetch distance from Google Maps directions URL
979e64a
import re
import requests
from bs4 import BeautifulSoup
def get_distance_from_google_maps(url):
"""
Fetches the HTML content of a Google Maps directions URL and extracts the distance dynamically.
Args:
url (str): The Google Maps directions URL.
Returns:
str: The distance in miles if found, otherwise None.
"""
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'
}
try:
response = requests.get(url, headers=headers)
response.raise_for_status() # Raise an exception for HTTP errors
html_content = response.text
# Use regex to find the distance string (e.g., "4.6 miles", "5.0 miles", etc.)
distance_match = re.search(r'([0-9.]+ miles?)', html_content) # Removed surrounding quotes
if distance_match:
distance_text = distance_match.group(1)
return distance_text
else:
return None
except requests.exceptions.RequestException as e:
print(f"Error fetching URL: {e}")
return None
if __name__ == "__main__":
url = 'https://www.google.com/maps/search/2782+McKee+Rd%2C+San+Jose%2C+CA+to+1380+Blossom+Hill+Rd%2C+San+Jose%2C+CA'
distance_text = get_distance_from_google_maps(url)
if distance_text:
print(f"Distance found: {distance_text}")
else:
print("Distance not found on the page.")