我已经使用正常运行的Chrome Selenium IDE扩展创建了代码。我创建的代码在Python中遵循相同的步骤。问题是:当我运行Python代码时,它无法通过ID来找到Selenium IDE没问题的元素。该元素位于iFrame中,因此我对此进行了说明,并且在加载iFrame时不会引发任何错误。
Here is the website where I'm trying to enter the codeword and email address.
下面是两个代码集的并排。
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
import time
options = webdriver.ChromeOptions()
options.add_argument('--ignore-certificate-errors')
options.add_argument("--test-type")
#options.add_argument("--incognito")
options.binary_location = r'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe'
driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:\Users\James\Documents\Scripts\lib\chromedriver.exe')
#driver.set_page_load_timeout(30)
actions = ActionChains(driver)
driver.get('https://alt949.radio.com/contest/holiday-feast-win-free-tickets#//')
for _ in range(2):
driver.find_element_by_tag_name('body').send_keys(Keys.PAGE_DOWN)
time.sleep(10)
#Switch to iframe
driver.switch_to.frame(driver.find_element_by_tag_name("iframe"))
#Set keyword
keyword_input = driver.find_element_by_id('ember634')
keyword_input.send_keys('keyword')
driver.switch_to.default_content()
谢谢!
答案 0 :(得分:1)
看起来“ ember” ID可以随时间变化(可能是由分布式CMS生成),因此需要一种不同的字段识别方法。以下代码将使您可靠地进入第一个屏幕。另外,由于它是一种交互式表单,因此我已切换为“等待”模型,而不是使用睡眠计时器。
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
# Set options to simplify flow and persist user data
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('disable-infobars')
chrome_options.add_argument('start-maximized')
chrome_options.add_experimental_option('prefs', {'credentials_enable_service': False, 'profile': {'password_manager_enabled': False}})
print("Loading page")
driver = webdriver.Chrome(options=chrome_options)
driver.get('https://alt949.radio.com/contest/holiday-feast-win-free-tickets#//')
print("Find frame")
element = WebDriverWait(driver, 30).until(EC.presence_of_element_located((By.XPATH, "//iframe[@data-ss-embed='iframe']")))
driver.switch_to.frame(element)
print("Enter codeword")
element = WebDriverWait(driver, 30).until(EC.visibility_of_element_located((By.CSS_SELECTOR, ".ssRegistrationField.ssTextboxField.ember-text-field.ember-view")))
element.click()
element.send_keys('codeword')
print("Enter email")
element = WebDriverWait(driver, 30).until(EC.visibility_of_element_located((By.CSS_SELECTOR, ".ssRegistrationField.ssEmailTextboxField.ember-text-field.ember-view")))
element.click()
element.send_keys('myemail@gmail.com')
print("Click Continue")
element = WebDriverWait(driver, 30).until(EC.presence_of_element_located((By.CLASS_NAME, 'ssButton')))
element.click()