【问题标题】:Python Selenium: How do I click a link in a drop down menu with css selector?Python Selenium:如何使用 CSS 选择器单击下拉菜单中的链接?
【发布时间】:2015-04-25 15:08:23
【问题描述】:

HTML 如下所示:

<span class="MenuIcons searchButton"></span>
    ... (some stuff)
    <a data-bind="" url="/ParagonLS/Search/Property.mvc/Index/1" tabdescription="RESIDENTIAL" subtabdescription="Criteria" subtabmaxallowed="3" targetex="" rel="" class=" SearchByClass1 " subtabgroup="true" subtabgroupadd="true" subtabstartindex="0" fullwindow="False" hideaddressbar="False">TEXT</a>

我可以使用:

driver.find_element_by_css_selector(".MenuIcons.searchButton")

但是由于 span 是一个下拉菜单,我需要进入内部元素,但不知道如何,因为它的类名周围有空格。我该怎么办?

【问题讨论】:

  • 我尝试使用 xpath,但由于空格在类名中,我得到错误。如果你能告诉我如何处理空格,那是一个可能的解决方案。
  • 可以link_text选择吗?
  • 我可以,但我需要找到一种方法让它不被隐藏。通过单击 元素与网站进行交互,然后出现下拉菜单,允许单击 元素。

标签: python css selenium


【解决方案1】:
import time
driver.find_element_by_css_selector(".MenuIcons.searchButton").click()
time.sleep(1)
driver.find_element_by_partial_link_text("TEXT").click()

你可以这样做并点击链接。

【讨论】:

  • 我得到“无法定位元素:{“method”:“link text”,“selector”:“TEXT”}”错误
  • @PythonNoob link text 到底是什么?
  • 感谢指正。我认为这更清洁
  • @Saifur 我猜他之前错过了点击操作。我也错过了:)
【解决方案2】:

我建议您改用xpath,因为class 包含空格。

//a[contains(@class,'SearchByClass1')]

基于文本的搜索也是另一种可能性。

//a[.='TEXT']

编辑 执行javascript,因为根据OP的评论隐藏了元素

test = driver.execute_script("return document.querySelector(\"a[class*='SearchByClass1']\").innerHTML;");
print(test)

打印

文字

【讨论】:

  • 这是否适用于最初隐藏的 属性?
  • 不这么认为。这是隐藏的吗?
  • 它隐藏在 元素下。这就是为什么我要先打开它,然后是
  • 你能执行javascript吗?
  • 感谢聊天倡议 :)
猜你喜欢
  • 2018-08-06
  • 2023-04-09
  • 2022-07-08
  • 2023-03-25
  • 2022-11-11
  • 1970-01-01
  • 1970-01-01
  • 2023-01-19
  • 1970-01-01
相关资源
最近更新 更多