Явное ожидание в загрузочной панели - PullRequest
0 голосов
/ 14 октября 2018

У меня есть следующая веб-структура

<tr class="group-head  clickable " id="date_matches-628" stage-value="14"><th colspan="5"><h3><span class="flag_16 left_16 austria_16_left">Austria - Landesliga</span></h3></th><th class="competition-link"> <a href="/national/austria/landesliga/c628/"><span>More…</span></a></th></tr>
<tr class="group-head  clickable " id="date_matches-1089" stage-value="19"><th colspan="5"><h3><span class="flag_16 left_16 austria_16_left">Austria - Jugendliga U18</span></h3></th><th class="competition-link"> <a href="/national/austria/jugendliga-u18/20182019/regular-season/r49380/"><span>More…</span></a></th></tr>

Если я щелкаю в каждом узле tr, он расширяется и загружается другая структура.Как это

<tr class="group-head  clickable  expanded loaded" id="date_matches-553" stage-value="12"><th colspan="5"><h3><span class="flag_16 left_16 austria_16_left">Austria - Regionalliga</span></h3></th><th class="competition-link"> <a href="/national/austria/regionalliga/c553/"><span>More…</span></a></th></tr>
<tr class="round-head expanded loaded"><th colspan="6"><h4><a href="/national/austria/regionalliga/20182019/mitte/r49359/">Mitte</a></h4></th></tr>
<tr class="even  expanded first last  match no-date-repetition" data-timestamp="1539518400" id="block_home_matches_29_match-2812137" data-competition="553"><td class="minute ">&nbsp;</td><td class="team team-a "><a href="/teams/austria/sv-lendorf/10948/" title="Lendorf">Lendorf</a></td><td class="score-time status"><a href="/matches/2018/10/14/austria/regionalliga/sv-lendorf/sc-weiz/2812137/?ICID=HP_MS_12_01">14 : 00</a></td><td class="team team-b "><a href="/teams/austria/sc-weiz/8729/" title="Weiz">Weiz</a></td><td class="events-button button first-occur"></td><td class="info-button button"><a href="/matches/2018/10/14/austria/regionalliga/sv-lendorf/sc-weiz/2812137/" title="Más información">Más información</a></td></tr>
<tr class="round-head expanded loaded"><th colspan="6"><h4><a href="/national/austria/regionalliga/20182019/west/r49361/">West</a></h4></th></tr>
<tr class="even  expanded first   match no-date-repetition" data-timestamp="1539518400" id="block_home_matches_29_match-2812947" data-competition="553"><td class="minute ">&nbsp;</td><td class="team team-a "><a href="/teams/austria/sv-bio-perlinger-worgl/173/" title="Wörgl">Wörgl</a></td><td class="score-time status"><a href="/matches/2018/10/14/austria/regionalliga/sv-bio-perlinger-worgl/sc-schwaz/2812947/?ICID=HP_MS_12_01">14 : 00</a></td><td class="team team-b "><a href="/teams/austria/sc-schwaz/10865/" title="Schwaz">Schwaz</a></td><td class="events-button button first-occur"></td><td class="info-button button"><a href="/matches/2018/10/14/austria/regionalliga/sv-bio-perlinger-worgl/sc-schwaz/2812947/" title="Más información">Más información</a></td></tr>
<tr class="odd  expanded    match no-date-repetition" data-timestamp="1539518400" id="block_home_matches_29_match-2812959" data-competition="553"><td class="minute ">&nbsp;</td><td class="team team-a "><a href="/teams/austria/fc-red-bull-salzburg-amateure/3367/" title="Anif / Salzburgo II">Anif / Salzbur…</a></td><td class="score-time status"><a href="/matches/2018/10/14/austria/regionalliga/fc-red-bull-salzburg-amateure/svg-reichenau/2812959/?ICID=HP_MS_12_02">14 : 00</a></td><td class="team team-b "><a href="/teams/austria/svg-reichenau/15753/" title="Reichenau">Reichenau</a></td><td class="events-button button first-occur"></td><td class="info-button button"><a href="/matches/2018/10/14/austria/regionalliga/fc-red-bull-salzburg-amateure/svg-reichenau/2812959/" title="Más información">Más información</a></td></tr>

Итак, я делаю следующее.Сначала я ищу «родительский» узел, и, если атрибут класса не содержит «расширенный загруженный», кликните по нему.

nodo=browser.find_element_by_xpath('.//tr[@id="{}"]'.format(ids))
if 'expanded loaded' not in league.get_attribute('class'):

try: league.click()
except WebDriverException:
    try:
        print('contingencia click')
        browser.execute_script("arguments[0].click();", league)

Проблема, иногда после нажатия на нужные мне узлы загружаются не полностью и выглядят как

<tr class=" loading event"></tr>

Поэтому, когда я делаю следующее для их поиска

partido=league.find_element_by_xpath('./following-sibling::tr[@class and not(contains(@class,"loading"))]')

, я получаю следующий узел, который нужно щелкнуть вместо тех, которыепредположительно загрузка.Итак, вкратце, как установить явное ожидание, чтобы программа вместо перехода к следующему не загружающему узлу ожидала, пока следующий узел изменит class=" loading event" на

<tr class="even  expanded first   match no-date-repetition" data-timestamp="1539518400" id="block_home_matches_29_match-2812947" data-competition="553"><td class="minute ">&nbsp;</td><td class="team team-a "><a href="/teams/austria/sv-bio-perlinger-worgl/173/" title="Wörgl">Wörgl</a></td><td class="score-time status"><a href="/matches/2018/10/14/austria/regionalliga/sv-bio-perlinger-worgl/sc-schwaz/2812947/?ICID=HP_MS_12_01">14 : 00</a></td><td class="team team-b "><a href="/teams/austria/sc-schwaz/10865/" title="Schwaz">Schwaz</a></td><td class="events-button button first-occur"></td><td class="info-button button"><a href="/matches/2018/10/14/austria/regionalliga/sv-bio-perlinger-worgl/sc-schwaz/2812947/" title="Más información">Más información</a></td></tr>

Спасибо

1 Ответ

0 голосов
/ 14 октября 2018

Похоже, ваш сайт использует Angular или что-то в этом роде ...

Так что я предлагаю сделать это, чтобы внедрить JavaScript ...

Я написал для этого функциюнадеюсь, это вам тоже поможет ...

from datetime import datetime, timedelta
from selenium.common.exceptions import WebDriverException
import time


def wait_until_angular(driver, seconds: int = 10) -> None:
    java_script_to_load_angular = "var injector = window.angular.element('body').injector(); " \
                              "var $http = injector.get('$http');" \
                              "return ($http.pendingRequests.length === 0);"
    end_time = datetime.utcnow() + timedelta(seconds=seconds)
    print("wait for Angular Elements....")
    while datetime.utcnow() < end_time:
        try:
            if driver.execute_script(java_script_to_load_angular):
                return
        except WebDriverException:
            continue
        time.sleep(0.1)
    raise TimeoutError("waiting for angular elements for too long")

Вы можете реализовать его в своем коде так, как считаете нужным!

Подробнее о execute_script можно прочитать здесь .

Надеюсь, это поможет!

...