我需要选择(打开)列表中的每部电影,从第一个到最后一个,一个一个,然后返回并打开列表中的下一个电影直到最后一部电影。但我遇到了一个问题,因为代码选择了最后一部电影而不是第一部电影。
我不知道如何选择第一个并重复该过程到列表中的每个电影。
这是代码:
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()
答案 0 :(得分:0)
您的代码需要大量重构,但我们试一试:
# 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
except: pass
这样您不知道代码何时失败希望它有所帮助!