首页 > 解决方案 > 在 Selenium Python 中更改页面后查找元素的问题

问题描述

我在 python 中使用网络刮板库作为 [Selenium]。我想提交一个表单(没有 AJAX 的多个表单)

所以,我写了这段代码:

from selenium import webdriver
import time

driver = webdriver.Chrome()
driver.get('https://exportgram.com/')

one = driver.find_element_by_xpath('//*[@id="home"]/form/div[1]/div/input[1]')
one.click()
one.send_keys('https://www.instagram.com/p/B6OCVnTglgz/')
two = driver.find_element_by_xpath('//*[@id="home"]/form/div[2]/button')
two.click()
time.sleep(3)


three = driver.find_element_by_xpath('//*[@id="home"]/form/div[2]/button')
three.click()

现在,我无法访问“三”,因为这在新页面上可用。

没有办法解决这个问题吗?

[注:点击“二”后,页面变为“ https://example.com/media.php ”]

标签: pythonseleniumweb-scrapingscrape

解决方案


如果单击第二个元素后,它会将您重定向到另一个页面,这意味着该表单已部分发送。浏览器加载新地址后,您将能够找到新的 DOM 树,因此您必须等待它出现。

您可以通过以下代码执行此操作:

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

timeout = 10
three = WebDriverWait(driver, timeout).until(EC.presence_of_element_located((By.XPATH, '//*[@id="home"]/form/div[2]/button')), 'Time out')
three.click()

推荐阅读