Невозможно выбрать раскрывающееся меню в приложении Python - PullRequest
0 голосов
/ 23 октября 2019

enter image description here

У меня есть скрипт для очистки значений с веб-сайта, с выпадающим меню при наведении, в котором нужно навести родительское меню, и раскрывающееся меню. опция вниз выбрана. Это работало отлично до нескольких дней назад. Но теперь происходит случайный сбой.

Это мой текущий код:

def select_dropdown():

    WebDriverWait(driver, 10).until(ec.visibility_of_element_located(
        (By.CSS_SELECTOR, "div.menu.menuTopCenter > ul > li:nth-child(3) > a")))
    investment = WebDriverWait(driver, 10).until(ec.element_to_be_clickable(
        (By.CSS_SELECTOR, "div.menu.menuTopCenter > ul > li:nth-child(3) > a")))
    actions.move_to_element(investment).perform()
    WebDriverWait(driver, 10).until(
         ec.element_to_be_clickable((By.CSS_SELECTOR, "li:nth-child(3) > div > div:nth-child(1) > a"))).click()

См. HTML-код родительского меню ниже:

 <a class="menuLink mainMenuItem" href="#" renderstyle="NONE" action="" 
 controller="" clientmodulesubid="0" renderlocation="" 
 clearcontentheader="False" 
 lobsystemuserids="Ls6EVzOdmMPVcdHshYcUbg==">Investment</a>

См. Ниже HTML-кодопция для выбора (подменю):

 <a class="menuLink mainMenuItem" href="#" renderstyle="REPLACE" action="Index" 
 controller="Portfolio" clientmodulesubid="6109" 
 renderlocation="contentHeaderContainer" clearcontentheader="True" 
 lobsystemuserids="Ls6EVzOdmMPVcdHshYcUbg==">Investment summary</a>

Это ошибка, которую я получаю:

Traceback (most recent call last):
  File "C:/Users/SChogle/PycharmProjects/Web Scraping All Sites (With BDay).py", line 55, in <module>
    select_dropdown()
  File "C:/Users/SChogle/PycharmProjects/Web Scraping All Sites (With BDay).py", line 29, in select_dropdown
    ec.element_to_be_clickable((By.CSS_SELECTOR, "li:nth-child(3) > div > div:nth-child(1) > a"))).click()
  File "C:\Users\SChogle\AppData\Roaming\Python\Python37\site-packages\selenium\webdriver\support\wait.py", line 80, in until
    raise TimeoutException(message, screen, stacktrace)
selenium.common.exceptions.TimeoutException: Message: 

Это полный HTML-код для родительского меню и всех подменю:

 <li class="has-children">
<a class="menuLink mainMenuItem" href="#" 
 renderstyle="NONE" action="" controller="" clientmodulesubid="0" 
 renderlocation="" clearcontentheader="False" 
 lobsystemuserids="8qWAwlpk6Jdje8MVVaH1Tw==">Investment</a>

<div class="subMenu"> 
 <div>

<a class="menuLink mainMenuItem" href="#" renderstyle="REPLACE" 
 action="Index" controller="Portfolio" clientmodulesubid="6109" 
 renderlocation="contentHeaderContainer" clearcontentheader="True" 
 lobsystemuserids="8qWAwlpk6Jdje8MVVaH1Tw==">Investment summary</a>
</div>

<div>
<a class="menuLink mainMenuItem" href="#" renderstyle="REPLACE" 
 action="GetLazyTransactionHistoryByAccountGroup" controller="Transactions" 
 clientmodulesubid="6108" renderlocation="contentHeaderContainer" 
 clearcontentheader="True" 
 lobsystemuserids="8qWAwlpk6Jdje8MVVaH1Tw==">Transaction history</a>
</div>

<div> 
 <a class="menuLink mainMenuItem" href="#" renderstyle="REPLACE" 
 action="LoadIncomeDistribution" controller="IncomeDistribution" 
 clientmodulesubid="7005" renderlocation="contentHeaderContainer" 
 clearcontentheader="True" lobsystemuserids="8qWAwlpk6Jdje8MVVaH1Tw==">Income 
 distribution</a>
</div>

<div>
<a class="menuLink mainMenuItem" href="#" 
 renderstyle="REPLACE" action="PortfolioFees" controller="Fees" 
 clientmodulesubid="6159" renderlocation="contentHeaderContainer" 
 clearcontentheader="True" lobsystemuserids="8qWAwlpk6Jdje8MVVaH1Tw==">Advisor 
 charges</a>
</div>

<div><a class="menuLink mainMenuItem" href="#" 
 renderstyle="REPLACE" action="GetRecurringInstructionsDetail" 
 controller="RecurringInstructions" clientmodulesubid="6158" 
 renderlocation="contentHeaderContainer" clearcontentheader="True" 
 lobsystemuserids="8qWAwlpk6Jdje8MVVaH1Tw==">Recurring instructions</a>
</div> 

<div>
<a class="menuLink mainMenuItem" href="#" renderstyle="REPLACE" 
 action="GenerateAdHocWebStatement_SAIP" controller="AdHocWebStatement" 
 clientmodulesubid="6121" renderlocation="contentHeaderContainer" 
 clearcontentheader="True" lobsystemuserids="8qWAwlpk6Jdje8MVVaH1Tw==">Investor 
 statement</a>
</div>

<div>
<a class="menuLink mainMenuItem" href="#" 
 renderstyle="REPLACE" action="GenerateAdHocWebStatement_SAIP" 
 controller="AdHocWebStatement" clientmodulesubid="8939" 
 renderlocation="contentHeaderContainer" clearcontentheader="True" 
 lobsystemuserids="8qWAwlpk6Jdje8MVVaH1Tw==">Tax certificate</a>
</div>
</div> 
 </li>

Я думаю, МОЖЕТ быть, происходит то, что скрипт пытается найти элемент до загрузки страницы, но я не уверен. Как я уже сказал, иногда это работает, а в другое время не получается.

Ответы [ 2 ]

1 голос
/ 23 октября 2019

Попробуйте select_menu метод ниже:

def select_menu(menu: str = None, submenu: str = None):
    menu_locator = f"//div[contains(@class,'menu')]//a[.='{menu}']"
    submenu_locator = f"{menu_locator}/ancestor::li[1]/div[@class='subMenu']//a[.='{submenu}']"

    wait = WebDriverWait(driver, 20)

    wait.until(lambda d: d.execute_script("return document.readyState === 'complete' && jQuery.active === 0;"))

    menu_element = wait.until(EC.element_to_be_clickable((By.XPATH, menu_locator)))
    actions.move_to_element(menu_element).perform()

    wait.until(EC.visibility_of_element_located((By.XPATH, submenu_locator))).click()

Как вызвать метод:

select_menu(menu="Investment", submenu="Investment summary")
0 голосов
/ 23 октября 2019

Вы можете попробовать отладку, чтобы сузить до решения с помощью этих шагов: 1. Повторите тот же блок кода, используя try catch:

count=0, max=5;
while(true){    
try{
    //drop down click
    }
    catch(Exception e){
    if(count++==max) throw e;
    }
}

также вы можете попробовать перезагрузить страницу и затем выполнить до ее успеха.

driver.navigate (). Refresh ();

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...