获取网站部分的id或xpath

2024-09-30 08:36:04 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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或类似的东西,以使代码适用于网站的其他部分


Tags: httpses网站wwwdriverseleniumloginaccount
2条回答
<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使所需的帧可用,并切换到它

  • 诱导WebDriverWait使所需的元素可单击

  • 您可以使用以下任一Locator Strategies

    • 使用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@stackoverflow.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@stackoverflow.com")
      
  • 注意:您必须添加以下导入:

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

winamax


参考文献

您可以在以下内容中找到一些相关讨论:

相关问题 更多 >

    热门问题