使用Python和Selenium进行Web抓取
我正在使用以下代码使用Python提交表单。 当输入的值正确时,它将重定向到名为使用Python和Selenium进行Web抓取,python,selenium,Python,Selenium,我正在使用以下代码使用Python提交表单。 当输入的值正确时,它将重定向到名为http://localhost/a/my.php。如何使用python检查页面是否重定向,以便知道输入的值是否正确 from selenium import webdriver webpage = r"http://localhost/a/" driver = webdriver.Chrome("C:\chromedriver_win32\chromedriver.exe") for i in range(10)
http://localhost/a/my.php
。如何使用python检查页面是否重定向,以便知道输入的值是否正确
from selenium import webdriver
webpage = r"http://localhost/a/"
driver = webdriver.Chrome("C:\chromedriver_win32\chromedriver.exe")
for i in range(10):
searchterm = i # edit me
driver.get(webpage)
sbox = driver.find_element_by_class_name("txtSearch")
sbox.send_keys(searchterm)
submit = driver.find_element_by_class_name("sbtSearch")
submit.click()
尝试使用当前的url:
driver.current_url
查找仅在加载新DOM后才存在的元素。如果你能找到它,你就进入了新的一页
try:
driver.find_element_by_class_name("txtSearch")
print("redirected to new page")
except NoSuchElementException:
print("oops, no redirect happened")
若要检查页面重定向是否正确,请使用带有正确链接的WebDriverWait(也称为“显式等待”)
预期条件
子句设置为以下条件之一:
蟒蛇:
url\u to\u be
:
WebDriverWait(driver, 10).until(EC.url_to_be("https://www.google.co.in/"))
WebDriverWait(driver, 10).until(EC.url_matches("https://www.google.co.in/"))
WebDriverWait(driver, 10).until(EC.url_changes("https://www.google.co.in/"))
url\u匹配
:
WebDriverWait(driver, 10).until(EC.url_to_be("https://www.google.co.in/"))
WebDriverWait(driver, 10).until(EC.url_matches("https://www.google.co.in/"))
WebDriverWait(driver, 10).until(EC.url_changes("https://www.google.co.in/"))
url\u包含
:
WebDriverWait(driver, 10).until(EC.url_contains("google"))
url\u更改
:
WebDriverWait(driver, 10).until(EC.url_to_be("https://www.google.co.in/"))
WebDriverWait(driver, 10).until(EC.url_matches("https://www.google.co.in/"))
WebDriverWait(driver, 10).until(EC.url_changes("https://www.google.co.in/"))
如果导航到新页面失败
el=driver.find_element_by_class_name(“txtSearch”)
应该会给你NoTouchElementException
Downvote??我可以知道为什么吗?我已经澄清了。您的第一种方法效率不高,因为如果新页面未打开,脚本会出现异常。请调整以捕获NoTouchElementException
,而不是使用is\u display()
。您可以使用驱动程序。当前url
确认它是您要查找的地址。如果它不起作用,也许你必须等待页面加载,只需添加一个time.sleep(x)
或其他什么。