How to get an element by tag name or id in Python and Selenium [duplicate]
Asked Answered
L

2

1

I am trying to get input using Python and Selenium, but it is showing me an error. How can I solve this error?

inputElement.send_keys(getStock.getStocklFunc()[0])

Error

inputElement = driver.find_element(by=By.CLASS_NAME, value='su-input-group')
NameError: name 'By' is not defined. Did you mean: 'py'?

I have tried with this line too, but it is showing a deprecation error:

find_element_by_tag_name
Lachrymal answered 23/5, 2022 at 1:52 Comment(0)
S
1

Use this when you want to locate an element by class name. With this strategy, the first element with the matching class name attribute will be returned. If no element has a matching class name attribute, a NoSuchElementException will be raised.

For instance, consider this page source:

<html>
  <body>
    <p class="content">Site content goes here.</p>
  </body>
</html>

The “p” element can be located like this:

content = driver.find_element_by_class_name('content')

https://selenium-python.readthedocs.io/locating-elements.html

Soccer answered 23/5, 2022 at 1:58 Comment(2)
It may be deprecated as well. From a comment: "find_element_by_* and find_elements_by_* are removed in Selenium 4.3.0. Use find_element instead.".Bimah
In fact, using a deprecated function in order to avoid the real problem (a very simple import problem) is not the way to go.Bimah
R
2

Make sure you have Selenium.By imported:

from selenium.webdriver.common.by import By

Do not add the "by=" and "value=" portion to the code.

WebDriverWait

It is also a better idea to locate your elements using the WebDriverWait method. Run the following command:

inputElement = WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CLASS_NAME, 'su-input-group')))

Make sure you also have these imports:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
Rosenberry answered 23/5, 2022 at 1:58 Comment(0)
S
1

Use this when you want to locate an element by class name. With this strategy, the first element with the matching class name attribute will be returned. If no element has a matching class name attribute, a NoSuchElementException will be raised.

For instance, consider this page source:

<html>
  <body>
    <p class="content">Site content goes here.</p>
  </body>
</html>

The “p” element can be located like this:

content = driver.find_element_by_class_name('content')

https://selenium-python.readthedocs.io/locating-elements.html

Soccer answered 23/5, 2022 at 1:58 Comment(2)
It may be deprecated as well. From a comment: "find_element_by_* and find_elements_by_* are removed in Selenium 4.3.0. Use find_element instead.".Bimah
In fact, using a deprecated function in order to avoid the real problem (a very simple import problem) is not the way to go.Bimah

© 2022 - 2024 — McMap. All rights reserved.