簡體   English   中英

IndexError:列表索引超出 python 中的循環范圍

[英]IndexError: list index out of range for loop in python

嗨 Everone 我想但是你在 59 時遇到這個錯誤

我的xlsx文件中有 1089 個項目

錯誤:

Traceback (most recent call last):
  File ".\seleniuminform.py", line 28, in <module>
    s.write(phone[i].text + "," + wevsite_link[i].text + "\n")
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


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

df = pd.read_excel('myfile.xlsx') # 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_")

    num_page_items = len(phone)
    with open("Sans Fransico.csv", 'a',encoding="utf-8") as s:

        for i in range(num_page_items):
            s.write(phone[i].text + "," + wevsite_link[i].text + "\n")

driver.close()
print ("Done")

關聯:

https://www.yelp.com/biz/daeho-kalbijjim-and-beef-soup-san-francisco-9?osq=餐廳

網站和電話出現錯誤:

在此處輸入圖像描述

我對 Selenium 不是很熟悉,所以我無法評論這方面。

第一次打開“Sans Francisco.csv”時,您讀取的內容沒有分配給變量。

至於您的錯誤,這是因為您的范圍是基於phone的長度,而不是wevsite_link的長度。 如果wevsite_linkphone短,你會得到一個錯誤。 簡單來說,您發現的網站鏈接少於電話號碼,但您的代碼假定您總是會找到完全相同數量的每個鏈接。

你能解釋一下你的代碼嗎? 你想做什么?

乍一看,我懷疑

phone = driver.find_elements_by_css_selector(".text--offscreen__373c0__1SeFX+ .text-align--left__373c0__2pnx_")

返回 0。您嘗試查找匹配項的 css 選擇器可能不准確。

似乎有些項目沒有電話,所以它發現的電話比網站少。

您應該首先找到所有".text--offscreen__373c0__1SeFX+" ,然后使用for -loop 在每個項目中分別搜索phonewebsite

使用try/except您可以識別項目是否沒有電話並使用空字符串作為電話號碼

for url in mylist:

    driver.get(url)

    all_items = driver.find_elements_by_css_selector(".text--offscreen__373c0__1SeFX+")

    for item in all_items:
        try:
            wevsite_link = item.find_element_by_css_selector(".link-size--default__373c0__1skgq")
            wevsite_link = wevsite_link.text
        #except selenium.common.exceptions.NoSuchElementException:
        except:
            wevsite_link = ''

        try:
            phone = item.find_element_by_css_selector(".text-align--left__373c0__2pnx_")
            phone = phone.text
        #except selenium.common.exceptions.NoSuchElementException:
        except:
            phone = ''

        with open("Sans Fransico.csv", 'a',encoding="utf-8") as s:
             s.write(phone + "," + wevsite_link + "\n")

我沒有 url 頁面,所以我無法測試它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM