Selenium Page Source is Missing Elements

℡╲_俬逩灬. 提交于 2019-12-07 16:03:47

问题


I have a basic Selenium script that makes use of the chromedriver binary. I'm trying to display a page with recaptcha on it and then hang until the answer has been completed and then store that in a variable for future use.

The roadblock I'm hitting is that I am unable to find the recaptcha element.

#!/bin/env python2.7
import os
from selenium import webdriver

driverBin=os.path.expanduser("~/Desktop/chromedriver")
driver=webdriver.Chrome(driverBin)
driver.implicitly_wait(5)
driver.get('http://patrickhlauke.github.io/recaptcha/')

Is there anything special needed to be able to see this element?

Also is there a way to grab the token after user solve without refreshing the page?

As it is now the input type of the recaptcha-token id is hidden. After solve a second recaptcha-token id is created. This is the value I wish to store in a variable. I was thinking of having a loop of checking length of found elements with that id. If greater than 1 parse. But I'm unsure whether the source updates per se.

UPDATE:

With more research it has to do with the nature of the element, particularly: with the tag: <input type="hidden". So I guess to rephrase my question, how does one extract the value of a hidden element.


回答1:


The element you are looking for (the input) is in an iframe. You'll need switch to the iframe before you can locate the element and interact with it.

import os
from selenium import webdriver

driver=webdriver.Chrome()
try:
    driver.implicitly_wait(5)
    driver.get('http://patrickhlauke.github.io/recaptcha/')

    # Find the iframe and switch to it
    iframe_path = '//iframe[@title="recaptcha widget"]'
    iframe = driver.find_element_by_xpath(iframe_path)
    driver.switch_to.frame(iframe)

    # Find the input element
    input_elem = driver.find_element_by_id("recaptcha-token")

    print("Found the input element: ", input_elem)

finally:
    driver.quit()


来源:https://stackoverflow.com/questions/38413427/selenium-page-source-is-missing-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!