【问题标题】:Python Seemingly Unavoidable IndexError and UnboundLocalErrorPython 看似不可避免的 IndexError 和 UnboundLocalError
【发布时间】:2018-05-05 15:10:35
【问题描述】:

我正在自动化将数据从我的网站导入 CSV 的过程。回溯可以在下面看到。我收到一个 NameError,指出在 if/elif 条件中未定义移动和办公室。

编辑:假设一个空白 Book1.csv

from selenium import webdriver
import time
import csv
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome()
driver.get("undisclosable")

driver.find_element_by_xpath("//input[@name='rad_region' and @value='far']").click()
time.sleep(2)
driver.find_element_by_xpath("//input[@name='rad_georegion' and @value='east']").click()
time.sleep(2)
driver.find_element_by_xpath("//input[@name='rad_manage' and @value='No']").click()
time.sleep(2)
driver.find_element_by_xpath('//*[@id="ModalPopupDiv"]/div/div[3]/div[1]/a').click()

class Search():
    with open(r'Book1.csv', 'r+', encoding='utf-8') as csvfile:
        csvreader = csv.reader(csvfile)
        next(csvreader)
        while True:
                for row in csvreader:
                    WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.ID, "searchKeyword")))
                    WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.ID, "go")))
                    driver.find_element_by_id('searchKeyword').clear()
                    time.sleep(1)
                    driver.find_element_by_id('searchKeyword').send_keys(row)
                    time.sleep(1)
                    driver.find_element_by_id('go').click()
                    time.sleep(1)

                    writer = csv.writer(csvfile)
                    tobesplit = str(driver.find_element_by_class_name('snippetContact').text)
                    emailandphone = tobesplit.split("  |  ")
                    try:
                        email = emailandphone[0]
                        office = emailandphone[1]
                        mobile = emailandphone[2]
                        writer.writerow([None, email, office, mobile])
                    except UnboundLocalError:
                        if mobile not in emailandphone:
                            writer.writerow([None, email, office])
                        elif office not in emailandphone:
                            writer.writerow([None, email])

这里是堆栈跟踪:

Traceback (most recent call last):
  File "C:/Users/s995648.CS/PycharmProjects/untitled/auto", line 39, in Search
    office = emailandphone[1]
IndexError: list index out of range

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:/Users/s995648.CS/PycharmProjects/untitled/auto", line 19, in <module>
    class Search():
  File "C:/Users/s995648.CS/PycharmProjects/untitled/auto", line 43, in Search
    if mobile not in emailandphone:
NameError: name 'mobile' is not defined

Process finished with exit code 1

【问题讨论】:

  • 嗨!欢迎来到堆栈交换。您能否重新表述这个问题以澄清哪个可能会引发哪个错误?你的代码有点不清楚。 str 没有在其中定义,而且在语法上也不正确。您可能想咨询MCVE 的要求
  • 欢迎来到 StackOverflow。请阅读并遵循帮助文档中的发布指南。 Minimal, complete, verifiable example 适用于此。在您发布 MCVE 代码并准确描述问题之前,我们无法有效地帮助您。我们应该能够将您发布的代码粘贴到文本文件中并重现您描述的问题。
  • 我很抱歉。我已经查看了 MCVE 并更新了我的一些代码,并将继续这样做。
  • 如果我的代码或我的文字没有描述我的问题,我很抱歉。这正是我的代码作为示例的样子。请随时给我建议,因为我是这个过程的新手。谢谢!
  • 只是为了澄清其他人在说什么:(1)有你看到的确切错误,包括堆栈跟踪,以及(2)一些我可以复制/粘贴到我的代码系统,这将运行并给出相同的错误。也许 (2) 没有那么简单,因为我们没有您的“Book1.csv”文件。

标签: python index-error


【解决方案1】:

1> 如果您正在解析的数据没有足够的由分隔符分隔的元素,那么您将收到以下错误并将移动到 except 块,这意味着 Mobile 变量分配永远不会发生,因此 except 块引发错误。我希望这很清楚。还有attaching an 示例,为了清楚起见,错误更早出现,他们建议在尝试结束时使用 else ,默认值除外(“none”可能适用于您的用例)

Traceback (most recent call last):
  File "C:/Users/s995648.CS/PycharmProjects/untitled/auto", line 39, in Search
    office = emailandphone[1]
IndexError: list index out of range

2> 在尝试访问值之前检查您的列表是否按照您的假设填充,最简单的方法是在分配后检查每个元素的长度,并进行相应的处理

【讨论】:

    猜你喜欢
    • 2021-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-08
    • 2020-12-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多