13

I'm trying to run a script in Selenium/Python that requires logins at different points before the rest of the script can run. Is there any way for me to tell the script to pause and wait at the login screen for the user to manually enter a username and password (maybe something that waits for the page title to change before continuing the script).

This is my code so far:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.keys import Keys
import unittest, time, re, getpass

driver = webdriver.Firefox()
driver.get("https://www.facebook.com/")

someVariable = getpass.getpass("Press Enter after You are done logging in")

driver.find_element_by_xpath('//*[@id="profile_pic_welcome_688052538"]').click()
4

2 回答 2

19

Use WebDriverWait. For example, this performs a google search and then waits for a certain element to be present before printing the result:

import contextlib
import selenium.webdriver as webdriver
import selenium.webdriver.support.ui as ui
with contextlib.closing(webdriver.Firefox()) as driver:
    driver.get('http://www.google.com')
    wait = ui.WebDriverWait(driver, 10) # timeout after 10 seconds
    inputElement = driver.find_element_by_name('q')
    inputElement.send_keys('python')
    inputElement.submit()
    results = wait.until(lambda driver: driver.find_elements_by_class_name('g'))
    for result in results:
        print(result.text)
        print('-'*80)

wait.until will either return the result of the lambda function, or a selenium.common.exceptions.TimeoutException if the lambda function continues to return a Falsey value after 10 seconds.

You can find a little more information on WebDriverWait in the Selenium book.

于 2013-06-04T21:11:14.290 回答
5
from selenium import webdriver
import getpass # < -- IMPORT THIS

def loginUser():
    # Open your browser, and point it to the login page
    someVariable = getpass.getpass("Press Enter after You are done logging in") #< THIS IS THE SECOND PART
    #Here is where you put the rest of the code you want to execute

然后每当你想运行脚本时,你输入loginUser()它就会做它的事情

这是有效的,因为它的getpass.getpass()工作原理完全一样input(),除了它不显示任何字符(它用于接受密码并且不向所有看着屏幕的人显示)

所以会发生什么是你的页面加载。然后一切都停止了,您的用户手动登录,然后返回 python CLI 并按 Enter。

于 2013-06-04T21:56:41.607 回答