如何使用try-except不断迭代列表?

2024-03-28 22:22:51 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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


Tags: csvnameiddfbydriverstatuselement
1条回答
网友
1楼 · 发布于 2024-03-28 22:22:51

不确定这里发生了什么,但代码中可能出错的一件事是,在迭代过程中,您正在更改正在迭代的内容。这是危险的,因为当您更改数据帧时,您的循环会被修改

iterrows上的文档:

You should never modify something you are iterating over. This is not guaranteed to work in all cases. Depending on the data types, the iterator returns a copy and not a view, and writing to it will have no effect.

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

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)

相关问题 更多 >