IndexError:迭代两个 webelement 列表时列表索引超出范围 [英] IndexError: list index out of range when iterating two webelements lists

查看:21
本文介绍了IndexError:迭代两个 webelement 列表时列表索引超出范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在终端上打印结果但收到此错误消息:

I am trying to print the result on the terminal but getting this error message:

IndexError: list index out of range

以下是代码,在此先感谢您的帮助.这个领域的真正初学者.

Below is the code, thanks in advance for your help. Truly beginner to this field.

import pandas as pd
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time

option = Options()
option.add_argument("--disable-infobars")
option.add_argument("start-maximized")
option.add_argument("--disable-extensions")
option.add_experimental_option("excludeSwitches", ['enable-automation'])

# Pass the argument 1 to allow and 2 to block
option.add_experimental_option("prefs", { 
    "profile.default_content_setting_values.notifications": 1 
})
driver = webdriver.Chrome(chrome_options=option, executable_path='C:\\Users\\Sheik\\Desktop\\web crawling\\chromedriver.exe')

driver.implicitly_wait(5000)

url = "https://www.yell.com/"

driver.get(url)

search_query_path = driver.find_element_by_xpath('''//*[@id="search_keyword"]''')
search_query_path.click()
search_query_path.send_keys("Garage Services")
search_city_path = driver.find_element_by_xpath('''//*[@id="search_location"]''')
search_city_path.click()
search_city_path.send_keys("London")
search_btn = driver.find_element_by_xpath('''//*[@id="searchBoxForm"]/fieldset/div[1]/div[3]/button''')
search_btn.click()


names = driver.find_elements_by_class_name("businessCapsule--name")
address = driver.find_elements_by_class_name("businessCapsule--address")

num_page_items = len(names)
for i in range(num_page_items):
    print(f"{names[num_page_items].text} : {address[num_page_items].text}")

driver.close()

推荐答案

您想使用索引 i 来迭代 namesaddress>,不是列表大小

You want to use the index i to iterate over names and address, not the list size

for i in range(num_page_items):
    print(f"{names[i].text} : {address[i].text}")

或者只是用 zip

for name, ad in zip(names, address):
    print(f"{name.text} : {ad.text}")

这篇关于IndexError:迭代两个 webelement 列表时列表索引超出范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆