【问题标题】:Python selenium click a button without idPython selenium单击没有id的按钮
【发布时间】:2018-10-20 21:30:14
【问题描述】:

我有这个代码

<a href="#" class="button expanded vote" style="background: rgb(51, 204, 102) none repeat scroll 0% 0%; border-radius: 5px;" onclick="Poll.sendAnswer("Programn2015","Answer1","Answer2")">Vote</a>

我能做什么?页面上还有其他按钮具有相同的类等,唯一的变量是

"Answer1","Answer2"

【问题讨论】:

  • “我能做什么?”...你尝试了什么?
  • 你想完成什么?
  • 发布相关的 HTML 或页面链接
  • 请与更多带有父标签或兄弟标签的html分享。

标签: python selenium selenium-webdriver xpath css-selectors


【解决方案1】:

要点击文本为投票的链接,您可以使用以下任一解决方案:

  • css_selector:

    driver.find_element_by_css_selector("a.button.expanded.vote[onclick*='Answer1'][onclick*='Answer2']").click()
    
  • xpath

    driver.find_element_by_xpath("//a[@class='button expanded vote' and contains(.,'Vote')][contains(@onclick,'Answer1') and contains(@onclick,'Answer2')]").click()
    

更新

诱导 WebDriverWait 使所需的元素可点击,如下所示:

  • css_selector:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a.button.expanded.vote[onclick*='Answer1'][onclick*='Answer2']"))).click()
    
  • xpath

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[@class='button expanded vote' and contains(.,'Vote')][contains(@onclick,'Answer1') and contains(@onclick,'Answer2')]"))).click()
    

注意:您必须添加以下导入:

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

【讨论】:

  • selenium.common.exceptions.NoSuchElementException: 消息:没有这样的元素:无法找到元素:{"method":"css selector","selector":"a.button.expanded.vote[ onclick*='Answer1'][onclick*='Answer2']"}(会话信息:chrome=70.0.3538.67)(驱动程序信息:chromedriver=69.0.3497.106(857b284701ddf7bef0f14fa76416cf7ca786b411),平台=Linux 4.15.0-36-generic x86_64)
  • 如果我用 firefox 编辑器复制 xpath,我会得到 " //*[@id="sondaggi"]/div/div[24]/div[2]/div/div[2]/ div/div[1]/a " 但是在做 chrome.find_element_by_xpath(' //*[@id="sondaggi"]/div/div[24]/div[2]/div/div[2]/div/div [1]/a').click() 在页面中找不到它
  • @MimmoBrescia 查看我更新的答案并告诉我状态
  • 嗨,我在“文件”/usr/local/lib/python2.7/dist-packages/selenium-2.53.6-py2.7.egg/selenium/webdriver/ support/wait.py",第 80 行,直到 raise TimeoutException(message, screen, stacktrace) selenium.common.exceptions.TimeoutException: Message: "
猜你喜欢
  • 1970-01-01
  • 2016-04-05
  • 1970-01-01
  • 1970-01-01
  • 2023-02-24
  • 2022-01-28
  • 2015-11-02
  • 1970-01-01
  • 2019-08-19
相关资源
最近更新 更多