How to click on the link by using Selenium + Python

Viewed 135

I am trying to open multiple links one by one by using Selenium + Python but not able to click on each link one by one and get data from each link.

I have tried:

for i in range(0, 1):

    list_links = driver.find_elements_by_tag_name('a')

    i = []     

    for i in list_links:

            link = i.get_attribute('href')
            my_list = [link]
            matching = [s for s in my_list if "https://www.magicbricks.com/propertyDetails/" in s]
            str_list = list(filter(None, matching))
            print (str_list)

I getting this after printing above code:

['https://www.magicbricks.com/propertyDetails/3-BHK-1865-Sq-ft-Multistorey-Apartment-FOR-Sale-Mulund-West-in-Mumbai&id=4d423335383538333735']
[]
['https://www.magicbricks.com/propertyDetails/1-BHK-520-Sq-ft-Multistorey-Apartment-FOR-Sale-Kandivali-West-in-Mumbai&id=4d423333323636353737']
[]
['https://www.magicbricks.com/propertyDetails/2-BHK-938-Sq-ft-Multistorey-Apartment-FOR-Sale-Sion-in-Mumbai&id=4d423332393937303531']
[]
['https://www.magicbricks.com/propertyDetails/2-BHK-672-Sq-ft-Multistorey-Apartment-FOR-Sale-Goregaon-West-in-Mumbai&id=4d423334393532373231']
[]
['https://www.magicbricks.com/propertyDetails/3-BHK-1325-Sq-ft-Multistorey-Apartment-FOR-Sale-Madh-in-Mumbai&id=4d423236343136393731']
[]

For click on link tried this but didn't work:

for link in matching:

       link.click()
       print (link)

Edit:

I have tried:

for s in my_list:

    if "https://www.magicbricks.com/propertyDetails/" in s:

        print (s)
        driver.find_element[s].click()

Getting error: driver.find_element[s].click() TypeError: 'method' object is not subscriptable.

or 
driver.find_elements_by_link_text(s).click()

Getting error: AttributeError: 'list' object has no attribute 'click'.

Please suggest something. Thanks in advance.

1 Answers

Because your list contains Strings but not Web Elements of Selenium (only after that you can do "click" action).

To do this you need to save also these objects from your list_links list (updated version according to "matching" links).

Code:

my_needed_links = []

list_links = driver.find_elements_by_tag_name("a")

# Get unique links.
for link in list_links:

    if "https://www.magicbricks.com/propertyDetails/" in link.get_attribute("href"):

        if link not in my_needed_links:

            my_needed_links.append(link)

# Go through of them and click on each.
for unique_link in my_needed_links:

    unique_link.click()
    # Switch to the tab.
    driver.switch_to_window(driver.window_handles[1])
    # Do some stuff inside tab.
    # Close the tab.
    driver.close()
    # Switch back to the main tab/window.
    driver.switch_to_window(driver.window_handles[0])

PS: Another way to do it without Web Elements: use JavaScript inside Web Driver and open links (your matching list) in tabs/windows.

Hope it helps you!

Related