首页 > 解决方案 > 如何使用 try except 继续遍历列表?

问题描述

我正在尝试使用 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)

它工作正常,直到它遇到异常,然后它只是一遍又一遍地循环相同的名称。我能做些什么来解决这个问题?

标签: pythonpandasselenium

解决方案


不确定这里发生了什么,但代码中可能出错的事情之一是您正在更改您正在迭代的事物,同时您正在迭代它。这是危险的,因为当您更改数据框时,您的循环会被修改。

从上的文档iterrows

永远不应该修改你正在迭代的东西。这不能保证在所有情况下都有效。根据数据类型,迭代器返回一个副本而不是一个视图,写入它不会有任何效果。

这是您的代码的“虚拟”版本,我会这样做:

import random
import pandas

# Some test dataframe (you can also load one from CSV of course)
df = pandas.DataFrame(
    [{"id": random.randint(0, 100), "name": random.randint(0, 100)} for _ in range(100)]
)


def status(row: pandas.Series):

    # Get some values from this row
    name = row["name"]

    # Do some work

    try:
        if name >= 80:
            raise Exception("Some exception is raised!")
        else:
            print("No problem")
            return True
    except Exception:
        try:
            if name >= 90:
                raise Exception("Even worse!")
            else:
                print("It's ok...")
                return False
        except Exception:
            print("The impossible has happened")
            return "Invalid"


# Apply the status function to every row
df["Status"] = df.apply(status, axis=1)

推荐阅读