如何在Selenium中通过类名查找元素?

3
在Selenium中,通过类名查找元素的语法是什么?请注意,我已经使用了以下语法:
link_elements = driver.find_elements_by_class_name("BM30N")

并且它给我以下错误信息:
C:\Users\David\Desktop\Selenium\Crawl.py:17: DeprecationWarning: find_elements_by_class_name is deprecated. Please use find_elements(by=By.CLASS_NAME, value=name) instead
  link_elements = driver.find_elements_by_class_name("BM30N")

当我使用:

link_elements=driver.find_elements(By.CLASS,'BM30N')

I get:

AttributeError: type object 'By' has no attribute 'CLASS'

但是上述语法对于ID和NAME完美地工作:
link_elements=driver.find_elements(By.NAME,'product-item')
link_elements=driver.find_elements(By.ID,'product-item')

有什么想法可以用什么正确的语法来按类搜索?
4个回答

2

您必须使用 Selenium 4

Selenium 4 中:

find_elements_by_class_name

其他find_elements_by_**已被弃用

您应该使用find_element(By.CLASS_NAME, "")代替。

因此,您的有效代码应该是:

link_elements = find_elements(By.CLASS_NAME, "BM30N")

这应该能帮助您解决问题。

1

变更

link_elements=driver.find_elements(By.CLASS,'BM30N')

to

link_elements=driver.find_elements(By.CLASS_NAME,'BM30N')

0

Java:

driver.findElement(By.className("input"));
&
driver.findElement(By.xpath("//input[@class='BM30N']"));

Python:

find_elements(By.CLASS_NAME, "BM30N")
&
driver.find_elements_by_class_name("BM30N")

0
别忘了正确导入“By”,我的VS Code只有在我以这种方式导入后才开始识别这个方法:
from selenium.webdriver.common.by import By

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接