第一次遇到 iFrame 之类的。刚刚学习了 Python 的基础知识,并创建了一个类似的脚本来登录网站。但是,对于这个特定的网站,我无法通过 iframe?网站:https://www.trademe.co.nz我尝试过使用 ChatGPT,但目前还没有成功。
我进入登录页面并尝试了以下代码:
> #importing modules.
from selenium import webdriver from selenium.webdriver.common.by import By
from selenium.common.exceptions
> import NoSuchElementException import time from
> selenium.webdriver.support.ui import WebDriverWait from
> selenium.webdriver.support import expected_conditions as EC
>
> #opening firefox and going to Google homepage. browser = webdriver.Firefox() browser.get('https://www.google.co.nz')
>
> browser.get('https://www.google.co.nz')
>
> #going to trademe.co.nz's website. search_elem = browser.find_element(By.CSS_SELECTOR, '#APjFqb') search_elem.click()
> time.sleep(3) search_elem.send_keys('trademe.co.nz')
> search_elem.submit() time.sleep(5) seek_elem =
> browser.find_element(By.CSS_SELECTOR, 'h3.LC20lb.MBeuO.DKV0Md')
> seek_elem.click()
> #congratulations, you have gained access to seeks homepage website.
>
> #signing into trademe.co.nz website. searchx_elem = browser.find_element(By.CSS_SELECTOR, '.tm-shell-main-nav__mtm-link')
> searchx_elem.click()
> ##iframe = browser.find_element(By.ID, 'tm-graffiti-iframe')
> ##time.sleep(3)
> ##browser.switch_to.frame(iframe)
> ##time.sleep(3)
> ##queryElement = browser.find_element(By.ID, 'Email')
> ##time.sleep(3)
> ##queryElement.send_keys('[email protected]')
> ## try:
> # Wait up to 10 seconds for the element to load
> email_input = WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.ID, 'Email')))
> email_input.send_keys("[email protected]") except:
> print("Couldn't locate the element")
您用注释标记覆盖的代码通常是正确的。尝试等待元素的存在,而不是立即与其交互。
使用 iFrame 元素时,您应该执行以下操作:
不幸的是,我无法访问您提供的网站,但这里有一个示例,说明如何在 the-internet.herokuapp
上使用 iFrame 内部的元素driver = webdriver.Firefox()
driver.maximize_window()
wait = WebDriverWait(driver, 10)
actions = ActionChains(driver)
try:
driver.get("https://the-internet.herokuapp.com/iframe")
# find iframe and switch to it
iframe = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, 'iframe.tox-edit-area__iframe')))
driver.switch_to.frame(iframe)
# now we are looking for the element inside the iframe
ptag = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, 'body > p')))
# do something with the located element
print(ptag.text)
ptag.send_keys("Writing some text to the <p> inside of the iframe")
# go back to the 'root', i.e. leave the iframe
driver.switch_to.default_content()
# try to access the element inside the iframe when you are not in the iframe
# THIS LINE WILL FAIL (!) BECAUSE WE ARE NOT IN THE IFRAME ANYMORE
wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, 'body > p')))
finally:
driver.quit()