IndexError:在python中,列表索引超出范围,但找不到某些内容

2024-06-17 12:43:54 发布

您现在位置:Python中文网/ 问答频道 /正文

如何修复IndexError: list index out of range

我正在做刮,但如果我的脚本找不到什么东西,它会给出这个错误

IndexError: list index out of range

我想继续下一个链接不中断,但我的脚本中断,而不是去与第二个网址

下面是我的python代码:

import pandas as pd
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException

plus = "+ "

with open("Sans Fransico.csv","r") as s:
    s.read()

df = pd.read_csv('Yelp+Scraping_Sans+Fransico.csv') # Get all the urls from the excel
mylist = df['Urls'].tolist() #urls is the column name

driver = webdriver.Chrome()
for url in mylist:

    driver.get(url)
    wevsite_link = driver.find_elements_by_css_selector(".text--offscreen__373c0__1SeFX+ .link-size--default__373c0__1skgq")
    phone = driver.find_elements_by_css_selector(".text--offscreen__373c0__1SeFX+ .text-align--left__373c0__2pnx_")



    items = len(wevsite_link)
    with open("Sans Fransico.csv", 'a',encoding="utf-8") as s:
        for i in range(items):
            if wevsite_link[i].text == '':
                s.write(phone[i].text + "\n")
            if [i] == '':
                s.write('N' + "," + 'N' + "\n")
                s.write('N' + "," + 'N' + "\n")
            if wevsite_link[i].text == '' and phone[i].text == '':
                s.write('' + "," + '' + "\n")
            else:
                s.write(phone[i].text + "," + wevsite_link[i].text + "\n")

driver.close()
print ("Done")

错误:

Traceback (most recent call last):
  File ".\seleniuminform.py", line 36, in <module>
    s.write(phone[i].text + "," + wevsite_link[i].text + "\n")
IndexError: list index out of range

Tags: csvtextfromimportasdriverseleniumlink
2条回答

缺少的项不是空字符串,它们不存在。您可以使用itertools.zip_longest对两个列表进行迭代

with open("Sans Fransico.csv", 'a',encoding="utf-8") as s:
    for combination in itertools.zip_longest(wevsite_link, phone):
        s.write(f'{combination[0].text if combination[0] else "N"}, {combination[1].text if combination[1] else "N"}\n')

如果预期会出现错误,可以将主循环包装为try/except´:

try:
   for url in mylist:
        .....

except Exception as e:
   print(e)

这将让你继续前进,仍然给你关于哪里出错的信息。你知道吗

相关问题 更多 >