【发布时间】: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