我正在进行网络爬网,以收集带有硒铬的网站中的评论。但是我有
IndexError:此代码中的代码驱动程序超出了列表索引
find_elements_by_class_name("item")[i].click()
完整代码为:
for i in range(0,len(item_number)):
driver.find_elements_by_class_name("item")[i].click() <gives error>
time.sleep(2.5)
driver.switch_to.window(driver.window_handles[1])
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
time.sleep(2.5)
driver.find_element_by_xpath("//*[@data-tab-id='review']").click()
time.sleep(1.5)
if driver.find_elements_by_class_name("review_tit")[1].find_element_by_class_name("count").text =='총 0개':
driver.close()
driver.switch_to.window(driver.window_handles[0])
else:
review_number = len(driver.find_elements_by_class_name("review_txt"))
if review_number== 20:
while review_number == 20:
review_number = len(driver.find_elements_by_class_name("review_txt"))
for j in range(review_number):
review.append(driver.find_elements_by_class_name("review_txt")[j].text)
score.append(int(driver.find_elements_by_xpath('//i[@class="star"]')[j+1].get_attribute("style").split(" ")[1].split("%")[0])/20)
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
time.sleep(1.5)
element = driver.find_elements_by_class_name('next_page')[0]
driver.execute_script("arguments[0].click();", element)
time.sleep(1.5)
review_number=len(driver.find_elements_by_class_name("review_txt"))
else:
for j in range(review_number):
review.append(driver.find_elements_by_class_name("review_txt")[j].text)
date.append(driver.find_element_by_id("_reviewList").find_elements_by_class_name("date")[j].text)
score.append(int(driver.find_elements_by_xpath('//i[@class="star"]')[j+1].get_attribute("style").split(" ")[1].split("%")[0])/20)
driver.close()
driver.switch_to.window(driver.window_handles[0])
错误是
IndexError:列表索引超出范围
从此代码
---> driver.find_elements_by_class_name("item")[i].click()
答案 0 :(得分:0)
根据文档here,如果未找到任何内容,该方法将返回一个空列表。空列表将中断[i]
列表访问。您确定要回来吗?将行分成两部分,然后尝试
result = driver.find_elements_by_class_name("item")
if( len(result) > 0):
result[i].click()
如果这可行,则可以考虑在出现此类错误时使用try catch块正常退出程序。