Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I locate the Google Maps URL present inside the iframe element via Selenium?

I wish to retrieve the Google Maps URL present inside the iframe element of a webpage https://villageinfo.in/andaman-&-nicobar-islands/nicobars/car-nicobar/arong.html.

Below is the sample url which I need from the iframe element. https://maps.google.com/maps?ll=9.161616,92.751558&z=18&t=h&hl=en-GB&gl=US&mapclient=embed&q=Arong%20Andaman%20and%20Nicobar%20Islands%20744301

I am unable to retrieve URL when I performed below steps. Page has only 1 iframe element.

iframe = driver.find_element_by_tag_name('iframe')
driver.switch_to.frame(iframe)

I even tried to retrieve all urls inside the element, but it gave Google Ads URLs apart from the one I require.

urls = driver.find_elements(By.TAG_NAME, 'a')
for url in urls:
    print(url.get_attribute('href'))

What should be the approach or methodology here to be tried?

Thanks in advance.

like image 943
Mohit Aswani Avatar asked Oct 17 '25 07:10

Mohit Aswani


1 Answers

You can't get elements inside Google Maps iframe because of browser CORS policy.

Reference to CORS

So Selenium gets empty iframe, because further requests to frame's contentWindow are rejected by browser.

However, you can simply construct google map link by parsing data from parent iframe.

from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from urllib.parse import urlparse, parse_qs

wait = WebDriverWait(driver, 10)
driver.get("https://villageinfo.in/andaman-&-nicobar-islands/nicobars/car-nicobar/arong.html")

map = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "iframe[src*='google.com/maps']")))
mapUrl = map.get_attribute('src')
parsed_url = urlparse(mapUrl)
query_params = parse_qs(parsed_url.query)
query_part = query_params.get('q')
search_url = "https://www.google.com/maps/place/{}".format(query_part[0])
driver.get(search_url)

Google Maps iframe url contains param 'q' that can be used to get needed location and search for it directly from Google endpoint.

So you just need to extract it and paste inside URL. In my code I get it via getting iframe src, getting it's param q and build new URL, using extracted param.

like image 102
Yaroslavm Avatar answered Oct 18 '25 22:10

Yaroslavm