簡體   English   中英

硒python無法獲取第一個元素

[英]Can't get the first element with selenium python

我需要選擇(打開)列表中的每部電影,從頭到尾開始,一次選擇一次,然后返回並打開列表中的下一部電影,直到最后一部電影。 但是我遇到了一個問題,因為代碼選擇了最后一部電影並打開了它而不是第一個。

我不知道如何選擇第一個,並對列表中的每個電影重復該過程。

這是代碼:

from selenium import webdriver
import time

URL = 'https://www.cineplanet.cl/peliculas'
XPATH_VER_MAS_PELICULAS = '//button'
ClASS_CARTELERA = 'movie-info-details'
XPATH_COMPRAR = '//div[@class="movie-info-details"]/div[@class="movie-info-details--wrapper"]/div[@class="movie-info-details--first-button-wrapper"]/button'
PATH = 'C:\\Program Files\\chrome-driver\\chromedriver.exe'

driver = webdriver.Chrome(PATH)
driver.get(URL)

def available_movies():
    try:
        select = driver.find_element_by_class_name(ClASS_CARTELERA)
        allOptions = select.find_elements_by_xpath(XPATH_COMPRAR)
        for option in allOptions:
            option.click()
    except:
        pass

print (driver.title)
time.sleep(5)

while True:
    try:
        if XPATH_VER_MAS_PELICULAS:
            driver.find_elements_by_xpath(XPATH_VER_MAS_PELICULAS)[-1].click()
            time.sleep(5)
        else:
            break
    except:
        break

available_movies()
time.sleep(2)
driver.quit()

您的代碼需要大量重構,但請嘗試一下:

# Keep doing this while we have movies to click
    while len(driver.find_element_by_class_name('movies-list--large-item')):
        # This will iterate through each movie
        for movie in driver.find_element_by_class_name('movies-list--large-item'):
            # Now get the button to see the movie details
            movie.find_element_by_class_name('cineplanet-icon_more').click()
            # Once you are in the movie details view do an assertion
            # Go back in the browser to the previous page
            driver.back()

        # If you reach this it means that you clicked all the movies in the current view
        # So click the View more movies button to go to the next page
        driver.find_element_by_css_selector('.movies-list--view-more-button-wrapper .call-to-action--text')

我在您的代碼中注意到了一些額外的事項:-不要使用time.sleep(5)是不可靠的。 使用Webdriver等待和預期條件等待元素出現:

http://selenium-python.readthedocs.io/waits.html

  • 不要使用Xpaths,它也不可靠。 如果可能,使用ID或類名
  • 浮出水面,您正在做的異常: except: pass這種方式,您將不知道代碼何時失敗
  • 以測試套件的方法來組織代碼,也許可以考慮將Unittest2用於python

希望能幫助到你!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM