Spaces:
Sleeping
Sleeping
shrijayan commited on
Commit ·
979e64a
1
Parent(s): 8e74260
Add function to fetch distance from Google Maps directions URL
Browse files
new.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
import requests
|
| 3 |
+
from bs4 import BeautifulSoup
|
| 4 |
+
|
| 5 |
+
def get_distance_from_google_maps(url):
|
| 6 |
+
"""
|
| 7 |
+
Fetches the HTML content of a Google Maps directions URL and extracts the distance dynamically.
|
| 8 |
+
|
| 9 |
+
Args:
|
| 10 |
+
url (str): The Google Maps directions URL.
|
| 11 |
+
|
| 12 |
+
Returns:
|
| 13 |
+
str: The distance in miles if found, otherwise None.
|
| 14 |
+
"""
|
| 15 |
+
headers = {
|
| 16 |
+
'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'
|
| 17 |
+
}
|
| 18 |
+
try:
|
| 19 |
+
response = requests.get(url, headers=headers)
|
| 20 |
+
response.raise_for_status() # Raise an exception for HTTP errors
|
| 21 |
+
|
| 22 |
+
html_content = response.text
|
| 23 |
+
|
| 24 |
+
# Use regex to find the distance string (e.g., "4.6 miles", "5.0 miles", etc.)
|
| 25 |
+
distance_match = re.search(r'([0-9.]+ miles?)', html_content) # Removed surrounding quotes
|
| 26 |
+
|
| 27 |
+
if distance_match:
|
| 28 |
+
distance_text = distance_match.group(1)
|
| 29 |
+
return distance_text
|
| 30 |
+
else:
|
| 31 |
+
return None
|
| 32 |
+
|
| 33 |
+
except requests.exceptions.RequestException as e:
|
| 34 |
+
print(f"Error fetching URL: {e}")
|
| 35 |
+
return None
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
if __name__ == "__main__":
|
| 39 |
+
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'
|
| 40 |
+
distance_text = get_distance_from_google_maps(url)
|
| 41 |
+
|
| 42 |
+
if distance_text:
|
| 43 |
+
print(f"Distance found: {distance_text}")
|
| 44 |
+
else:
|
| 45 |
+
print("Distance not found on the page.")
|