怪异的Python Selenium按钮单击行为

时间:2016-05-09 11:37:15

标签: python selenium web-scraping

我试图点击的部分:

<ul class="btns right">
<li><a href="javascript:void(0)" onclick="hr_expand_event_tab_all(&quot;&quot;)" class="expand-all" id="btn_expand_all_10580503">View All Cards</a></li>
</ul>

我觉得很简单。但我似乎错过了一些东西。

问题现在更新了一点。 xpath不是我尝试使用更正的xpath的问题,它与使用类名相同。 CSS隐藏了几个版本的按钮,但是它实际上通过xpath或类名找到了一个common.exception。

我已检查页面是否已正确加载且元素在那里。我有一张支票,要等到装满整个页面并截屏以确定。

loadbutton = Driver.find_element_by_xpath("//a[@class='expand-all']")

给出:

<class 'selenium.common.exceptions.ElementNotVisibleException'>

所以我试着用锚点找到一个onclick:

loadbutton = Driver.find_element_by_xpath("//li[contains(@onclick, 'View All Cards')]")

结果相同。我已经尝试了一些正则表达式来捕捉id变化,但我不确定我在哪里出错了。有一个onlick,它已加载,但我看不到它。

我很感激任何可以告诉我在这个问题上我做错了什么。

/更新:

原来有按钮的多个版本,有些是可见的,有些则不是。

我循环:

loadbutton = Driver.find_elements_by_xpath("//a[@class='expand-all']")
for button in loadbutton:
  print "button found"

它出现了多个结果。之前的那些是隐藏的,但最后的那些肯定显示在我的浏览器和屏幕截图上。所以我希望早期的失败并添加一个.click()并尝试:除了:它们都失败了。没想到。

进一步更新:

所以我跑了这个:

loadbutton = Driver.find_elements_by_xpath("//a[@class='expand-all']")
for button in loadbutton:
  print "button found"
  try:
    button.click()
  except:
    e = sys.exc_info()[0]
    print e

第一对夫妇给了我这个:

<class 'selenium.common.exceptions.ElementNotVisibleException'>

确定CSS正在隐藏它。显示的最后两个给出了这个:

<class 'selenium.common.exceptions.WebDriverException'>

所以它可以看到它们。它不会点击它们。 “常见例外”似乎没有太大帮助。

1 个答案:

答案 0 :(得分:2)

尝试使用此xpath(使用代码块更新SO站点删除了我的*)

//*[contains(concat(' ', @class, ' '), ' btns right ')]//*[contains(concat(' ', @class, ' '), ' expand-all ') and contains(text(), 'View All Cards')]

提供一些等待元素可点击的内容(建议隐式)。

我只用于java,但我在这里提到python here它可能会有所帮助!!

from selenium.webdriver.support import expected_conditions as EC

wait = WebDriverWait(driver, 10)
button = wait.until(EC.element_to_be_clickable((By.XPATH,'//*[contains(concat(' ', @class, ' '), ' btns right ')]//*[contains(concat(' ', @class, ' '), ' expand-all ') and contains(text(), 'View All Cards')]')))
button.click()


Even if the above thing fails, try this

形成这些链接link1link2

driver.execute_script("document.getElementsByClassName('expand-all')[0].click();")

在所需元素上注入人工CLICK,删除(注释)所有其他代码

可能是你的应用程序属于link2 OP:)