import selenium
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
browser = webdriver.Chrome()
browser.get('https://wj.qq.com/s/2214142/51db') # survey link
# First page - click "Next" button, it works
NextButton = browser.find_element_by_class_name('survey_nextpage') # got to next page
NextButton.click()
# Second page - click one of the scale button between 1-5
answers = browser.find_elements_by_class_name('star_item') # it works
answers[4].click() # it works
NextButton.click() # it works
# Third page - click one of the scale button as 2nd page
answers = browser.find_elements_by_class_name('star_item') # either with or without this statement, the next line will give error
answers[2].click() # it throws error
NextButton.click()
从第2页开始,每个网页包含1-5比例(5个按钮),格式完全相同。当代码运行到第三页时,它将给出如下错误:
ElementNotVisibleException: element not visible
(Session info: chrome=67.0.3396.87)
(Driver info: chromedriver=2.40.565498 (ea082db3280dd6843ebfb08a625e3eb905c4f5ab),platform=Windows NT 10.0.17134 x86_64)
由于我已经在第2页上找到了答案选项,所以我不知道为什么它适用于第3页(与第2页完全相同的比例格式)。
如何重复使用相同的方法为具有相同调查格式的接下来的5个页面选择选项?
任何建议都将不胜感激。谢谢!
答案 0 :(得分:1)
问题是页面上有70个元素,其类名称为star_item
。而且,当您尝试单击第二页answers[2].click()
时,实际上它是第一页中的第三个元素,这当然不再可见。因此,您必须更改选择器,或使用以下解决方案:
我看到每个页面上都有5个元素,因此您可以按以下方式处理问题:
add = 0 # value to add
NextButton = browser.find_element_by_class_name('survey_nextpage') # got to next page
NextButton.click()
# Second page - click one of the scale button between 1-5
# you don't have to locate this elements on every page, only once
answers = browser.find_elements_by_class_name('star_item') # locate all elements
answers[4 + add].click() # it will peek an item 4 plus add value
add += 5 # increase the value at 5
NextButton.click()
# Third page - click one of the scale button as 2nd page
answers[2 + add].click()
add += 5
NextButton.click()
代码说明:如果我们知道每页上有5个元素,并且使用此定位器选择70个元素,则70/5 = 14个页面中有此元素。因此,为了能够单击特定页面上70的右边元素,我们引入了一个变量,该变量对已经完成的页面进行计数。此变量为add
。通过每页后,它将增加到5。