我正在自动化将数据从我的网站导入 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