Как получить закрывающий тег в селене - PullRequest
0 голосов
/ 11 марта 2020

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

Единственная разница в интерактивности vs non-clickable, кажется, закрывающий тег disabled>.

Моя идея состояла в том, чтобы создать некоторое время l oop и нажимать на кнопку, пока не исчезнет отключенный тег, но я не уверен, как получить этот тег в первую очередь.

Даже если кнопка отключена, Selenium не выдает ошибку «Элемент не взаимодействует», поэтому я не думаю, что смогу go по этому маршруту.

airport_list = []
fees_list = []

airports = ["https://www.aopa.org/destinations/business/13035#fees", "https://www.aopa.org/destinations/business/35555#fees"]

for a in airports:
    driver.get(a)
    time.sleep(3)

    # Click dropdown
    driver.find_element_by_xpath('//div[@class = "mat-select-arrow"]').click()
    time.sleep(1)
    # Select "All aircraft"
    driver.find_elements_by_xpath('//span[@class = "mat-option-text"]')[8].click()
    time.sleep(2)

    try:        

        # Check if fees are available
        driver.find_element_by_xpath('//mat-row[@class = "mat-row ng-star-inserted"]')

        #Scrape each row
        fees_table = driver.find_elements_by_xpath('//mat-row[@class = "mat-row ng-star-inserted"]')
            for fee in fees_table:
            fees_list.append(fee.text)
            airport_list.append(a)

        #Click on "Next" button

        driver.find_elements_by_xpath('//span[@class = "mat-button-wrapper"]')[4].click()
        time.sleep(2)

    except:
        fees_list.append("This location has not disclosed fees or does not charge fees.")
        airport_list.append(a)           

driver.close()

Ответы [ 2 ]

0 голосов
/ 11 марта 2020

Вместо перехода на следующую страницу используйте максимальный предел строки, как показано в приведенном ниже коде. Кроме того, вам не нужно использовать try, кроме block -

for a in airports:
    driver.get(a)
    time.sleep(3)

    # Click dropdown
    driver.find_element_by_xpath('//div[@class = "mat-select-arrow"]').click()
    time.sleep(1)
    # Select "All aircraft"
    driver.find_elements_by_xpath('//span[@class = "mat-option-text"]')[8].click()
    time.sleep(3)

    # select 100 Items per page if items are present
    if len(driver.find_elements_by_xpath(".//mat-select[@aria-label='Items per page:']")) > 0 :
        driver.find_element_by_xpath(".//mat-select[@aria-label='Items per page:']").click()
        time.sleep(3)
        driver.find_element_by_xpath(".//span[@class='mat-option-text' and text()='100']/parent::mat-option").click()

    # Scrape each row
    fees_table = driver.find_elements_by_xpath('//mat-row[@class = "mat-row ng-star-inserted"]')
    for fee in fees_table:
        fees_list.append(fee.text)
    print(fees_list)

        # if needed then Click on "Next" button using this xpath and apply same for loop as above
        #driver.find_elements_by_xpath(".//button[@aria-label='Next page']").click()
driver.close()
0 голосов
/ 11 марта 2020

Мне удалось извлечь максимальное количество элементов из нижней части таблицы, разделить это число на 10 и округлить до ближайшего числа. Затем я использую это число для перебора диапазона.

airport_list = []
fees_list = []

airports = ["https://www.aopa.org/destinations/business/13035#fees"]

for a in airports:
    driver.get(a)
    time.sleep(3)

    # Click dropdown
    driver.find_element_by_xpath('//div[@class = "mat-select-arrow"]').click()
    time.sleep(1)
    # Select "All aircraft"
    driver.find_elements_by_xpath('//span[@class = "mat-option-text"]')[8].click()
    time.sleep(2)

    try:        
        # Check if fees are available
        driver.find_element_by_xpath('//mat-row[@class = "mat-row ng-star-inserted"]')

        # Get number of items
        number_of_items = driver.find_element_by_xpath('//div[@class = "mat-paginator-range-label"]').text.split()[-1]
        #print(number_of_items)

        if float(number_of_items) >= 11:
            number_of_button_clicks = math.ceil(float(number_of_items)/10)
        else:
            number_of_button_clicks = 0
        #print(number_of_button_clicks)

        for click in range(0, number_of_button_clicks):
            #Scrape each row
            fees_table = driver.find_elements_by_xpath('//mat-row[@class = "mat-row ng-star-inserted"]')
            for fee in fees_table:
                fees_list.append(fee.text)
                airport_list.append(a)

            #Click on "Next" button

            driver.find_elements_by_xpath('//span[@class = "mat-button-wrapper"]')[4].click()
            time.sleep(2)

    except:
        fees_list.append("This location has not disclosed fees or does not charge fees.")
        airport_list.append(a)


#print(fee_list)
#print(airport_list)            

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