[英]Selenium Python - How do I handle the exceptions on popups regardless of the order and handle a null or empty search
我有一個遍歷列表的搜索。 對於搜索需要額外點擊彈出窗口的情況,我添加了一個嘗試。 但是,嵌套嘗試的順序,除了會導致問題取決於彈出窗口的進入順序。使用當前代碼,應用程序被卡在 optionModalContent 彈出窗口上。 此外,如果完成了 null 或空的搜索,則應用程序將超時。 處理空/空搜索的最佳方法是什么? 例如搜索 C06 或 0。
下面是我的代碼,其中包含應用程序的精簡版本。
from selenium import webdriver
import pandas as pd
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait, TimeoutException
import time
appended_data = []
classlist = ['C',
'C01',
'BETA BLOCKING AGENTS', #optionModalContent
'ANTIADRENERGIC AGENTS', #spellingModal
'C02',
'C06', #no search results timesout need to know how to handle this
'C07',
'Vitamins' #handled by optionModalContentTable
]
time.sleep(1)
with webdriver.Chrome('C:\Program Files\Chrome Driver\chromedriver.exe') as driver: ## uses the content manager by using with webdriver.Chrome, improves performance
for search in classlist:
page = f"https://mor.nlm.nih.gov/RxClass/search?query={search}"
driver = webdriver.Chrome('C:\Program Files\Chrome Driver\chromedriver.exe')
driver.get(page)
modal_wait = WebDriverWait(driver, 4)
try:
modal_el = modal_wait.until(EC.element_to_be_clickable((By.ID, 'synModalContent'))) ## handles last popup if the search isn't exact
modal_el.find_element(By.CSS_SELECTOR, 'div.nameEntry').click()
try:
modal_el = modal_wait.until(EC.element_to_be_clickable((By.ID, 'optionModalContent'))) ## handles popup that requires you to select a line item
modal_el.find_element(By.CSS_SELECTOR, 'ul.uloption').click()
except:
try:
modal_el = modal_wait.until(EC.element_to_be_clickable((By.ID, 'spellingModal'))) ## handles popup to suggest spelling
modal_el.find_element(By.CSS_SELECTOR, 'div.nameEntry').click()
except:
modal_el = modal_wait.until(EC.element_to_be_clickable((By.ID, 'optionModalContentTable'))) ##handles first popup window on search if there are multiple classes for vitamin
modal_el.find_element(By.CSS_SELECTOR, 'div.nameEntry').click()
pass
except TimeoutException:
pass
table = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, 'tr.dbsearch')))
classid = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.table-responsive div.propText strong:nth-child(2)"))).text
classname = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.table-responsive div.propText strong:nth-child(1)"))).text
classtype = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.table-responsive div.propText strong:nth-child(3)"))).text
filename = classname[0:30]+'.csv'
df = pd.read_html(driver.page_source)[1].iloc[:,:-1].assign(ClassID=classid, ClassName=classname, ClassType=classtype)
appended_data.append(df)
driver.quit()
appended_data = pd.concat(appended_data)
appended_data.to_csv('testcategorization.csv')
我知道我的問題將出現在我的嵌套嘗試中。 我已經移動了一些東西並添加了通行證,但無論應用程序最終會卡在其中一個搜索上的順序如何。 無論順序如何,處理所有彈出窗口的最佳方法是什么?
也許有一個更好的方法來 go 關於嘗試和除外。 此外,如果搜索沒有返回任何結果,我不確定如何處理。
我正在尋找的最終結果是讓我的應用程序運行而不會卡在列表中的彈出窗口上,而不管它的運行順序如何。
現在,這就是讓我前進的原因:
從當前 url 中獲取搜索鍵,並將代碼置於try
塊下的if elif else
中。 您仍然可以通過在每個if elif else
語句中使用try/except
來改進它。
title = driver.current_url
print(title)
try:
if "BETA%20BLOCKING%20AGENTS" in title:
modal_el = modal_wait.until(EC.element_to_be_clickable(
(By.ID, 'optionModalContent'))) ## handles popup that requires you to select a line item
modal_el.find_element(By.CSS_SELECTOR, 'ul.uloption').click()
elif "ANTIADRENERGIC%20AGENTS" in title:
modal_el = modal_wait.until(
EC.element_to_be_clickable((By.ID, 'spellingModal'))) ## handles popup to suggest spelling
modal_el.find_element(By.CSS_SELECTOR, 'div.nameEntry').click()
modal_wait.until(EC.element_to_be_clickable((By.XPATH, "//*[@id='optionModalContent']//li"))).click()
elif "Vitamins" in title:
modal_el = modal_wait.until(EC.element_to_be_clickable((By.ID,
'optionModalContentTable'))) ##handles first popup window on search if there are multiple classes for vitamin
modal_el.find_element(By.CSS_SELECTOR, 'div.nameEntry').click()
modal_wait.until(EC.element_to_be_clickable((By.XPATH, "//*[@id='optionModalContent']//li"))).click()
else:
modal_el = modal_wait.until(
EC.element_to_be_clickable((By.ID, 'synModalContent'))) ## handles last popup if the search isn't exact
modal_el.find_element(By.CSS_SELECTOR, 'div.nameEntry').click()
仍在檢查如何處理no classes found
的情況。 如果我破解它,將在此處作為更新發布。 將檢查我的空閑時間。 我希望感謝您編寫的代碼。 除了打開一個額外的瀏覽器實例之外,它非常精簡,但我會說這是一個非常好的實例。 我今天從你那里學到了一些東西。
更新:我嘗試了一些替代方案,它奏效了。 請檢查以下代碼。 它設法通過從搜索列表中搜索每個項目來獲得結果,同時處理C06
。
我使用了很多用於調試目的的打印語句。 隨意刪除它們。 此外,我在幾次使用time.sleep
來處理警報。 嘗試減少它,看看它是否有效。
for search in classlist:
page = f"https://mor.nlm.nih.gov/RxClass/search?query={search}"
driver = webdriver.Chrome(ChromeDriverManager().install())
driver.get(page)
time.sleep(5)
try:
WebDriverWait(driver, 3).until(EC.alert_is_present())
alert = driver.switch_to.alert
alert.accept()
print("alert accepted")
except TimeoutException:
print("no alert")
title = driver.current_url
print(title)
modal_wait = WebDriverWait(driver, 4)
try:
if "BETA%20BLOCKING%20AGENTS" in title:
print("betablocker")
modal_el = modal_wait.until(EC.element_to_be_clickable(
(By.ID, 'optionModalContent'))) ## handles popup that requires you to select a line item
modal_el.find_element(By.CSS_SELECTOR, 'ul.uloption').click()
elif "ANTIADRENERGIC%20AGENTS" in title:
print("diuretic")
modal_el = modal_wait.until(
EC.element_to_be_clickable((By.ID, 'spellingModal'))) ## handles popup to suggest spelling
modal_el.find_element(By.CSS_SELECTOR, 'div.nameEntry').click()
modal_wait.until(EC.element_to_be_clickable((By.XPATH, "//*[@id='optionModalContent']//li"))).click()
elif "Vitamins" in title:
print("vitamin")
modal_el = modal_wait.until(EC.element_to_be_clickable((By.ID,
'optionModalContentTable'))) ##handles first popup window on search if there are multiple classes for vitamin
modal_el.find_element(By.CSS_SELECTOR, 'div.nameEntry').click()
modal_wait.until(EC.element_to_be_clickable((By.XPATH, "//*[@id='optionModalContent']//li"))).click()
else:
print("others")
modal_el = modal_wait.until(
EC.element_to_be_clickable((By.ID, 'synModalContent'))) ## handles last popup if the search isn't exact
modal_el.find_element(By.CSS_SELECTOR, 'div.nameEntry').click()
except Exception as e:
print(f"No tables found in {search}")
continue
控制台 Output(最終結果):
Process finished with exit code 0
更新 2:根據查詢創建者的評論處理嘗試/除外。
for search in classlist:
page = f"https://mor.nlm.nih.gov/RxClass/search?query={search}"
driver = webdriver.Chrome(ChromeDriverManager().install())
driver.get(page)
time.sleep(2)
try:
WebDriverWait(driver, 3).until(EC.alert_is_present())
alert = driver.switch_to.alert
alert.accept()
print("alert accepted")
print(f"No tables found in {search}")
continue
except TimeoutException:
print("no alert")
modal_wait = WebDriverWait(driver, 4)
try:
modal_el = modal_wait.until(
EC.element_to_be_clickable((By.ID, 'synModalContent'))) ## handles last popup if the search isn't exact
modal_el.find_element(By.CSS_SELECTOR, 'div.nameEntry').click()
except:
try:
modal_el = modal_wait.until(EC.element_to_be_clickable(
(By.ID, 'optionModalContent'))) ## handles popup that requires you to select a line item
modal_el.find_element(By.CSS_SELECTOR, 'ul.uloption').click()
except:
try:
modal_el = modal_wait.until(
EC.element_to_be_clickable((By.ID, 'spellingModal'))) ## handles popup to suggest spelling
modal_el.find_element(By.CSS_SELECTOR, 'div.nameEntry').click()
except:
modal_el = modal_wait.until(EC.element_to_be_clickable((By.ID,
'optionModalContentTable'))) ##handles first popup window on search if there are multiple classes for vitamin
# modal_el.find_element(By.CSS_SELECTOR, 'div.nameEntry').click()
modal_el.find_element(By.CSS_SELECTOR, 'div.nameEntry').click()
pass
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.