在继续运行之前,如何让Selenium/Python等待用户登录?

JSt*_*tew 9 python selenium

我正在尝试在Selenium/Python中运行一个脚本,在脚本的其余部分可以运行之前需要在不同的位置登录.有没有办法告诉脚本暂停并在登录屏幕上等待用户手动输入用户名和密码(可能是在继续脚本之前等待页面标题更改的东西).

到目前为止这是我的代码:

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()
Run Code Online (Sandbox Code Playgroud)

unu*_*tbu 13

使用WebDriverWait.例如,这会执行Google搜索,然后在打印结果之前等待某个元素出现:

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)
Run Code Online (Sandbox Code Playgroud)

wait.until将返回lambda函数的结果,或者selenium.common.exceptions.TimeoutException如果lambda函数在10秒后继续返回Falsey值.

您可以WebDriverWaitSelenium一书中找到更多信息.


Teh*_*ris 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
Run Code Online (Sandbox Code Playgroud)

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

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

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