在被重定向到网页后找不到元素



这不是确切的代码,但基本上错误是相同的。我使用python selenium来访问一个网站。有两个按钮。第一个将我重定向到一个页面。第二个按钮在我重定向到的那个页面上。由于某种原因,它说第二页上的按钮找不到。

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
options = webdriver.ChromeOptions()
options.add_experimental_option('excludeSwitches', ['enable-logging'])
driver = webdriver.Chrome(options=options, executable_path=r"C:UsersangelDownloadschromedriver.exe")
#techwithtim cause why not 
driver.get('https://www.techwithtim.net')
driver.implicitly_wait(3)
#first button
buttonPath = r"/html/body/div[2]/div/div[2]/aside[2]/div/ul/li[2]/a"
try:
button = driver.find_element(By.XPATH, buttonPath)
button.click()
except:
print("bad")
#second button on newly redirected webpage
secondPath = r"/html/body/nav/div/div/ul/li[1]/a"
secondButton = driver.find_element(By.CLASS_NAME, secondPath)
secondButton.click()

我把我的代码修改成上面最小的形式,但它仍然不适合我。我在第二个按钮上做了一个尝试,除了块,它打印了页面源,打印了第一个网页的html,而不是重定向的。我该如何解决这个问题?

对不起,如果这是一个容易的问题,因为我仍然是非常新的编程,任何帮助是感激的。

试试这个:

# Needed libs
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
#Define web driver as a Chrome driver and navigate. I am in Linux, in Windows you can define your browser in the same way you were doing it.
driver = webdriver.Chrome()
driver.maximize_window()
url = 'https://www.techwithtim.net'
driver.get(url)
# First button
buttonPath = "//li[@id='menu-item-402']/a"
button = WebDriverWait(driver, 30).until(EC.presence_of_element_located((By.XPATH, buttonPath)))
button.click()

# Second button on newly redirected webpage
secondPath = "//li[@id='menu-item-156']/a"
secondButton = WebDriverWait(driver, 30).until(EC.presence_of_element_located((By.XPATH, secondPath)))
secondButton.click()

2建议:

  1. 试着用简单的定位器定位你的元素,如果你看到我的xpath,它真的很简单。
  2. 总是,当你必须与一个元素交互时,尽量等待它,直到它准备好。

相关内容

  • 没有找到相关文章

最新更新