获取网站部分的 id 或 xpath

Getting id or xpath of parts of a website

我想使用 selenium 登录网站 https://www.winamax.es/account/login.php?redir=/apuestas-deportivas。情况是我没有找到 xpath/id/text 来成功获取下一个代码 运行:

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
options = webdriver.ChromeOptions()
options.add_argument("window-size=1920,1080")
options.add_argument('--disable-blink-features=AutomationControlled')
driver=webdriver.Chrome(options=options,executable_path=r"chromedriver.exe")
driver.get("https://www.winamax.es/account/login.php?redir=/apuestas-deportivas")
WebDriverWait(driver=driver, timeout=15).until(
    lambda x: x.execute_script("return document.readyState === 'complete'")
)
upload_field = driver.find_element_by_xpath("//input[@type='email']")

我不仅想要此示例的特定 xpath,而且我更喜欢获取 xpath 的方法或类似的方法以使代码适用于网站的其他部分

<iframe id="iframe-login" data-node="iframe" name="login" scrolling="auto" frameborder="1" style="min-height: 280px; width: 100%;"></iframe>

您的元素位于 iframe 中。切换到它。

WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.ID, "iframe-login")))

导入

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait 
from selenium.webdriver.support import expected_conditions as EC

完整的工作代码。

wait = WebDriverWait(driver, 10)
driver.get("https://www.winamax.es/account/login.php?redir=/apuestas-deportivas")
wait.until(EC.frame_to_be_available_and_switch_to_it((By.ID, "iframe-login")))
upload_field = wait.until(EC.element_to_be_clickable((By.XPATH, "//input[@type='email']")))
upload_field.send_keys("stuff")

email 元素在 <iframe> 中,因此您必须:

  • 诱导 WebDriverWait 所需的 帧可用并切换到它.

  • 诱导 所需的 元素可点击

  • 您可以使用以下任一项:

    • 使用CSS_SELECTOR:

      driver.get("https://www.winamax.es/account/login.php?redir=/apuestas-deportivas")
      WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"iframe#iframe-login")))
      WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input[type='email']"))).send_keys("scraper@whosebug.com")
      
    • 使用XPATH:

      driver.get("https://www.winamax.es/account/login.php?redir=/apuestas-deportivas")
      WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@id='iframe-login']")))
      WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@type='email']"))).send_keys("scraper@whosebug.com")
      
  • 注意:您必须添加以下导入:

     from selenium.webdriver.support.ui import WebDriverWait
     from selenium.webdriver.common.by import By
     from selenium.webdriver.support import expected_conditions as EC
    
  • 浏览器快照:


参考

您可以在以下位置找到一些相关讨论:

  • Switch to an iframe through Selenium and python