Using own variable in WebDriverWait. Selenium. Python

ghz 3days ago ⋅ 2 views
link = div.find_element_by_tag_name('a')

How can I use this in the statement

link = WebDriverWait(driver, 10).until(EC.visibility_of_element_located(div.find_element_by_tag_name('a')))

This, doesn't work.

Answer

The issue with your code is that you are calling div.find_element_by_tag_name('a') immediately in the WebDriverWait statement, but what you need to do is pass a locator (a condition) to WebDriverWait.

Here is the correct way to use WebDriverWait in this scenario:

Correct Code:

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

link = WebDriverWait(driver, 10).until(
    EC.visibility_of_element_located((By.TAG_NAME, 'a'))
)

Explanation:

  • EC.visibility_of_element_located: This condition waits until the specified element is visible.
  • (By.TAG_NAME, 'a'): This is a tuple representing the locator for the element. By.TAG_NAME indicates that you want to locate the element by its tag name (a in this case). You need to pass a tuple with the method (By.TAG_NAME) and the value ('a').

If you want to locate the anchor (<a>) tag inside a specific div, and div is already located, you should use the find_element approach but with the correct syntax.

If you want to locate an anchor tag within a specific div:

You can first locate the div and then use WebDriverWait to wait for the anchor tag inside that div:

div = WebDriverWait(driver, 10).until(
    EC.visibility_of_element_located((By.ID, "your_div_id"))  # or another locator for the div
)
link = WebDriverWait(div, 10).until(
    EC.visibility_of_element_located((By.TAG_NAME, 'a'))
)

Summary:

  • WebDriverWait should wait for a condition that returns a locator (such as a tuple with By strategy and value).
  • In your case, the correct way is to use EC.visibility_of_element_located((By.TAG_NAME, 'a')) in WebDriverWait.

Let me know if that clears things up!