使用硒无法“非HTML按钮”

时间:2019-10-08 16:24:09

标签: python selenium

我正尝试使用python和selenium来单击元素而没有成功,就像我想单击按钮元素时一样。

python --version
Python 2.7.16

print selenium.__version__
3.141.0

chromedriver --version
ChromeDriver 2.36

chromium-browser --version
Chromium 65.0.3325.181

这是标签:

<a data-fblog="the_button" href="javascript:" id="the_btn" class="the_btn" title="Goto">Goto</a>

(显然没有定义为按钮)

这是负责点击该标签的python部分:

chrome_options = Options()
chrome_options.add_argument("--disable-extensions")
chrome_options.add_argument("--headless")
chrome_options.add_argument("--disable-gpu")
driver = webdriver.Chrome('PATHTOCRHROMEDRIVER/chromedriver',options=chrome_options)
driver.get('https://www.urltogetinfo.com')

try:
    the_button = driver.find_element_by_id('the_btn')
    the_button.click()
    #Also tried these aproaches without sucess:
    #the_button = driver.find_element_by_id('the_btn').send_keys(Keys.RETURN)
    #the_button = driver.find_element_by_id('the_btn').send_keys(Keys.ENTER)
    sleep(5)
except:
    print("Problem clicking the button")
    #would like to log the exception here
    pass

我可能做错了什么?

2 个答案:

答案 0 :(得分:1)

尝试以下选项

  1. 尝试在Webdriver初始化之后或单击元素之前添加隐式等待。 driver.implicitly_wait(15)
  2. 尝试添加明确的等待按钮

WebDriverWait(driver, 3).until(EC.presence_of_element_located((By.ID, "the_btn")))

  1. 检查按钮是否存在于iframe中。如果按钮存在于iframe广告代码中,请在单击按钮之前切换到iframe

答案 1 :(得分:1)

您可以尝试在元素存在时调用WebDriverWait,然后在此处单击Javascript。

the_button = WebDriverWait(driver, 15).until(EC.presence_of_element_located((By.ID, "the_btn")))
driver.execute_script("arguments[0].click();", the_button)