Python Selenium doesn't find element when passing a variable

Viewed 317

I am able to find and click an href with this method and passing the string "facebook.com"

driver.find_element_by_link_text("facebook.com")

but when I use a variable to store the string like this

fb_url = "facebook.com"

and then I try to pass it like this

driver.find_element_by_link_text(fb_url)

I get this output

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"link text","selector":"facebook.com"}

I already tested it with driver.find_element_by_partial_link_text, driver.find_element_by_xpath, driver.findElement(By.linkText())

but always get the same results, they work by passing the string "facebook.com" but if I pass the variable fb_url it fails. I already searched for similar questions but none of the answers seem to work, I have tried them all.

full code

from selenium import webdriver
import time
import random

def url_random():
    with open("choice.txt") as f:
     lines = f.readlines()
     aleatorio = random.choice(lines)
     return aleatorio

def search_url():
    driver = webdriver.Chrome()
    driver.get('https://testingcodeclicks.blogspot.com/2021/05/facebook.html')
    time.sleep(3)
    fb_url = url_random()
    driver.find_element_by_link_text(fb_url).click()

search_url()

the file choice.txt in def url_random(): only has a line of text which is facebook.com

1 Answers

To click Facebook.com link use xpath:

driver.find_element_by_xpath("//a[contains(@href, 'facebook.com')]").click()

Explanation: facebook.com is the value of href attribute.

In the context of your task it would look like:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome(executable_path='/snap/bin/chromium.chromedriver')
driver.get("https://testingcodeclicks.blogspot.com/2021/05/facebook.html")
fb_url = "facebook.com\n"
url = fb_url.rstrip()
locator = f"//a[contains(@href, '{url}')]"
#  print(type(locator))
#  print(type(url))
#  print(locator)
WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.XPATH, locator)))
driver.find_element_by_xpath(locator).click()
# driver.close()
# driver.quit()

I edited my answer. facebook.com was not passed as string to locator. I left debugging code commented for you to check it by yourself. Also, I added rstrip() to fb_url. It cuts \n. If even it won't work, try using strip(). Check here for more details: How can I remove a trailing newline?

Related