【问题标题】:find_element_by_class_name for multiple classes [duplicate]多个类的find_element_by_class_name [重复]
【发布时间】:2017-11-29 07:18:54
【问题描述】:

Python/Django的API中的Selenium有函数driver.find_element/elements_by_class_name(),但是没有写是否可以用于多个类 我需要选择具有 bj、bd、bi 等多个类的元素 如果可能,怎么做?

【问题讨论】:

  • 使用 find_elements_by_class_name。
  • 你试过了吗?请阅读How to Ask,尤其是关于minimal reproducible example(MCVE)和How much research effort is expected?的部分,这将帮助您调试自己的程序并自己解决问题。如果您这样做并且仍然卡住,您可以返回并发布您的 MCVE、您尝试过的内容以及执行结果(包括任何错误消息),以便我们更好地帮助您。还提供指向页面和/或相关 HTML 的链接。
  • 是的,我试试。不同的东西。但我认为可能存在文档中未描述的某些功能/接收。
  • 您可以使用循环并使用 .format() 来获取每个类。

标签: python django api selenium parsing


【解决方案1】:

答案是否定的,您不能将driver.find_element_by_class_name ()driver.find_elements_by_class_name () 与多个类名一起使用。它只接受单个类名。

但是,您可以使用find_elements_by_xpathfind_element_by_css_selector 方法来实现查找具有多个类名的元素。

例如下面的代码将使用两个不同的类名在谷歌网站上查找元素。

url= "http://google.com"
driver = webdriver.Chrome()
driver.get(url)
driver.find_elements_by_xpath("//*[@class='sfibbbc' or @class='jsb']")
# Following line will result in error 
driver.find_elements_by_class_name("sfibbbc jsb")

【讨论】:

  • 我喜欢为此编程。仅通过课程和所有尝试。但是使用 xpath 更容易。谢谢
  • 我发现用 css 选择器更简洁(当然我用 java )...findElements(By.cssSelector(".sfibbbc.jsb"))
  • 仅供参考@1234 在 python 中的建议如下:driver.find_elements_by_css_selector(". sfibbbc. jsb")
猜你喜欢
  • 2012-01-07
  • 2022-01-18
  • 1970-01-01
  • 2016-05-20
  • 2014-08-07
  • 1970-01-01
  • 2015-06-19
  • 2012-06-17
相关资源
最近更新 更多