简体   繁体   English

IndexError:在 python 中列出超出范围的索引,而未找到某些内容

[英]IndexError: list index out of range in python while something not found

How to Fix IndexError: list index out of range如何修复IndexError: list index out of range

I'm Doing Scraping But if My Script Can't Find Something It Give This Error我正在抓取,但如果我的脚本找不到它会给出这个错误

IndexError: list index out of range

I Want To Continue to next link not break but my script break and not go with second url我想继续下一个链接不中断但我的脚本中断而不是 go 和第二个 url

Here is my python code:这是我的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")

ERROR:错误:

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

if the errors are expected, you can wrap your main loop in a try/except´:如果错误是预期的,您可以将主循环包装在 try/except´ 中:

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

except Exception as e:
   print(e)

That will let you keep going and still give you info about where errors occured.这将使您继续前进,并仍然为您提供有关错误发生位置的信息。

Missing items are not empty string, they don't exist.缺少的项目不是空字符串,它们不存在。 You can use itertools.zip_longest to iterate over both lists您可以使用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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM