[英]how to relogin and link to specified webpage with selenium python
我在同一個網站上有兩個密碼A和B,有時用密碼A登錄,有時用密碼B登錄,無論使用密碼A還是B,登錄后我需要鏈接到一個指定的web頁面,但登錄后總是停止並做不執行后續代碼。 下面是我的代碼,我嘗試了不同的功能但失敗了,我不知道這些代碼有什么問題,請幫助,非常感謝!
from selenium import webdriver
import time
driver = webdriver.Chrome()
def login():
driver.get('website_url')
while True:
driver.find_element_by_xpath('//*[@id="Account"]').send_keys('Username')
time.sleep(2)
driver.find_element_by_xpath('//*[@id="Password"]').send_keys('Password A')
time.sleep(2)
driver.find_element_by_xpath('//*[@class="loginBtn"]').click()
time.sleep(3)
# if password A login failed, using password B
try:
strl = driver.find_element_by_xpath('//*[@class="field-validation-error"]').text
if strl == "Password Error":
driver.find_element_by_xpath('//*[@id="Account"]').clear()
time.sleep(2)
driver.find_element_by_xpath('//*[@id="Account"]').send_keys('Username')
time.sleep(2)
driver.find_element_by_xpath('//*[@id="Password"]').send_keys('Password B')
time.sleep(2)
driver.find_element_by_xpath('//*[@class="loginBtn"]').click()
time.sleep(3)
except:
print('Login Successfully!')
return driver
login()
一直停在這里,不執行后續代碼
# This is where the main execution code starts.
def main():
driver.get('webpage_url')
main()
我看到了一些錯誤:
1- try-except的原因是什么? 我在代碼中看不到任何異常。
2- 您將driver
定義為全局變量,但您從login
function 返回它。因此,這似乎不合邏輯。 此外,您沒有將此返回值分配給任何變量。
3- 使用time.sleep()
是一種不好的做法,但我認為這些僅用於調試。
4- while True:
語句創建一個無限循環。
我的建議:
1- 你應該完全刪除try-except並且只使用if-else為此。
2- 從login
function 中刪除return
語句。
3- 定義程序的入口點,例如if __name__ == '__main__':
。
4- 刪除while True:
創建無限循環的語句或小心使用它。
放在一起:
from selenium import webdriver
import time
driver = webdriver.Chrome()
def login():
driver.get('website_url')
driver.find_element_by_xpath('//*[@id="Account"]').send_keys('Username')
time.sleep(2)
driver.find_element_by_xpath('//*[@id="Password"]').send_keys('Password A')
time.sleep(2)
driver.find_element_by_xpath('//*[@class="loginBtn"]').click()
time.sleep(3)
# if password A login failed, using password B
strl = driver.find_element_by_xpath('//*[@class="field-validation-error"]').text
if strl == "Password Error":
driver.find_element_by_xpath('//*[@id="Account"]').clear()
time.sleep(2)
driver.find_element_by_xpath('//*[@id="Account"]').send_keys('Username')
time.sleep(2)
driver.find_element_by_xpath('//*[@id="Password"]').send_keys('Password B')
time.sleep(2)
driver.find_element_by_xpath('//*[@class="loginBtn"]').click()
time.sleep(3)
print('Login Successfully!')
def main():
login()
driver.get('website_url')
if __name__ == '__main__':
main()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.