找不到firebug的Python Selenium Xpath

时间:2016-10-18 19:35:27

标签: python selenium xpath

我正在尝试使用selenium登录ESPN网站。这是我到目前为止的代码

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

driver = webdriver.Firefox()
driver.maximize_window()

url = "http://www.espn.com/fantasy/"
driver.get(url)

login_button = driver.find_element_by_xpath("/html/body/div[6]/section/section/div/section[1]/div/div[1]/div[2]/a[2]")
login_button.click()

try:
    element = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.XPATH, "/html/body/div[2]/div/div/section/section/form/section/div[1]/div/label/span[2]/input")))
except:
    driver.quit()

基本上,有2个步骤,首先我必须单击登录按钮然后我必须填写表单。目前,我点击登录按钮,表格弹出,但我找不到表格。我一直在使用firebug来获取其他SO问题中建议的xpath。我对硒的了解并不多,所以我不确定在哪里看

2 个答案:

答案 0 :(得分:2)

这对我有用,首先切换到iframe。请注意,您需要在输入凭据后切换回iframe。

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

driver = webdriver.Firefox()
driver.maximize_window()

url = "http://www.espn.com/fantasy/"
driver.get(url)

login_button = driver.find_element_by_xpath("/html/body/div[6]/section/section/div/section[1]/div/div[1]/div[2]/a[2]")
login_button.click()

iframe = driver.find_element_by_id("disneyid-iframe")
driver.switch_to.frame(iframe)

try:
    element = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.XPATH, "/html/body/div[2]/div/div/section/section/form/section/div[1]/div/label/span[2]/input")))
    element.send_keys("my username")

    import time
    time.sleep(100)
finally:
    driver.quit()

答案 1 :(得分:2)

尝试使用

driver.switch_to_frame('disneyid-iframe')
# handle authorization pop-up
driver.switch_to_default_content() # if required