簡體   English   中英

如何使Selenium / Python在繼續運行之前等待用戶登錄?

[英]How can I make Selenium/Python wait for the user to login before continuing to run?

我正在嘗試在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()

使用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)

wait.until或者返回lambda函數,或一個的結果selenium.common.exceptions.TimeoutException如果lambda函數繼續10秒后返回一個Falsey值。

您可以在Selenium書中找到有關WebDriverWait更多信息。

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並按回車。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM