我正在尝试使用pandas遍历csv文件,并使用selenium通过网站查看列表。但是,一旦遇到异常,它就会在同一个项目上反复循环
以下是我迄今为止所尝试的:
from selenium.webdriver.common.keys import Keys
import pandas as pd
driver = webdriver.Chrome()
url = 'website.com'
df = pd.read_csv('sample.csv')
def status():
for ind, row in df.iterrows():
name = row['id']
name_id = row['name']
print(name)
global name_loc
name_loc = df[df['name']==name].index.values
driver.get(url)
driver.find_element_by_xpath('//*[@id="something"]').send_keys(name_id)
driver.find_element_by_xpath('//*[@id="something"]').send_keys(name)
driver.find_element_by_xpath('//*[@id="something"]').send_keys(Keys.RETURN)
try:
status = driver.find_element_by_xpath('//*[@id="something').text
if status == "true":
status = "True"
df.loc[name_loc, "Status"] = status
print("Status: True")
except Exception:
pass
try:
global inactive_status
inactive_status = driver.find_element_by_xpath('something').text
ins_text = "Registration Information"
if inactive_status == ins_text:
status1 = "False"
df.loc[name_loc, "Status"] = status1
print("Status: False")
except Exception:
status2 = "Invalid"
df.loc[name_loc, "Status"] = status2
print(status2)
status()
print(df)
df.to_csv('Report.csv', index=False)
它工作正常,直到遇到异常,然后它只是一次又一次地循环相同的名称。我能做些什么来解决这个问题
不确定这里发生了什么,但代码中可能出错的一件事是,在迭代过程中,您正在更改正在迭代的内容。这是危险的,因为当您更改数据帧时,您的循环会被修改
从
iterrows
上的文档:这是您代码的“虚拟”版本,我会这样做:
相关问题 更多 >
编程相关推荐