如何使用Selenium在新页面

时间:2017-02-01 21:47:21

标签: python selenium selenium-webdriver webdriver

我使用此代码创建脚本填充数据本身

Snippet#1完成后,在按下登录后在同一个水龙头中打开一个新页面。我想使用代码片段#2来查找按钮代码刷新并单击它但每次出现错误时都显示在此之后:

Snippet#1

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import re
import time

browser = webdriver.Firefox()
browser.get('the url')

user = browser.find_element_by_css_selector('#Frm_Username')
user.send_keys('admin')

password = browser.find_element_by_css_selector('#Frm_Password')
password.send_keys('admin')

clickLogin = browser.find_element_by_css_selector('#LoginId')
clickLogin.click()

browser.implicitly_wait(20)

Snippet#2

link = browser.find_element_by_css_selector('#Btn_ReFresh')        
link.click()

错误:

Traceback (most recent call last):
  File "C:/Users/myName/Desktop/loginTest1.py", line 30, in <module>
    link = browser.find_element_by_css_selector('#Btn_ReFresh')
  File "C:\Users\myName\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 437, in find_element_by_css_selector
    return self.find_element(by=By.CSS_SELECTOR, value=css_selector)
  File "C:\Users\myName\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 752, in find_element
    'value': value})['value']
  File "C:\Users\myName\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 236, in execute
    self.error_handler.check_response(response)
  File "C:\Users\myName\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 192, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: {"method":"css selector","selector":"#Btn_ReFresh"}
Stacktrace:
    at FirefoxDriver.prototype.findElementInternal_ (file:///C:/Users/myName/AppData/Local/Temp/tmpkiy2vz8t/extensions/fxdriver@googlecode.com/components/driver-component.js:10770)
    at fxdriver.Timer.prototype.setTimeout/<.notify (file:///C:/Users/myName/AppData/Local/Temp/tmpkiy2vz8t/extensions/fxdriver@googlecode.com/components/driver-component.js:625)

我想要的只是找到一个元素并在新页面中单击它,该页面在脚本登录后在同一个点击中打开?

1 个答案:

答案 0 :(得分:0)

当您使用selenium时,您应该考虑在每个页面中您都是浏览器变量应该引用该页面,例如,在这里您使用browser.get()转到网址,但是当您使用clicklogin.click()时,您将转到另一个页面,所以浏览器不引用该页面所以当你使用link = browser.find_element_by_css_selector('#Btn_ReFresh')它给你错误和错误说无法找到元素只是因为浏览器不在该页面,解决问题我建议你看看当你点击登录浏览器的网址时,然后传递那个网址的browser.get。例如,如果它是a标记,请参阅此元素的href属性并将其传递给browser.get()