无法继续列表除了通过

Can't continue list with except pass

我的代码必须继续如果假设除了(他们寻找列表中的下一项)但我收到错误...

尝试了很多想法,但 none 成功了。现在我有了那个代码:

        def process_cpf_list(self):
            cpfs = self.sheet.col_values(self.cpf_col)[1:]

            bot_url = BOT(cpfs)

            nomes, idades, beneficios, concessoes, salarios, bancoss, bancoscard, consigs, cards = bot_url.search_cpfs()
            print("Atualizando...")

            for i in range(len(nomes)):
                try:
                    self.sheet.update_cell(i + 2, self.nome_col, nomes[i])
                    self.sheet.update_cell(i + 2, self.age_col, idades[i])
                    self.sheet.update_cell(i + 2, self.beneficio_col, beneficios[i])
                    self.sheet.update_cell(i + 2, self.concessao_col, concessoes[i])
                    self.sheet.update_cell(i + 2, self.salario_col, salarios[i])
                    self.sheet.update_cell(i + 2, self.bancos_col, bancoss[i])
                    self.sheet.update_cell(i + 2, self.bancocard_col, bancoscard[i])
                    self.sheet.update_cell(i + 2, self.consig_col, consigs[i])
                    self.sheet.update_cell(i + 2, self.card_col, cards[i])

                except NoSuchElementException:
                    print('CPF Invalido')
                    pass

cpf_updater = CpfSearch('TESTE')
cpf_updater.process_cpf_list()

它给我错误:

Traceback (most recent call last):
  File "C:/Users/MOISA/PycharmProjects/inss2/cpf_updater.py", line 54, in <module>
    cpf_updater.process_cpf_list()
  File "C:/Users/MOISA/PycharmProjects/inss2/cpf_updater.py", line 34, in process_cpf_list
    nomes, idades, beneficios, concessoes, salarios, bancoss, bancoscard, consigs, cards = bot_url.search_cpfs()
  File "C:\Users\MOISA\PycharmProjects\inss2\k_bot.py", line 66, in search_cpfs
    nome = self.driver.find_element_by_xpath("/html/body/main[1]/div[1]/div[1]/div[1]/div[1]/h2").text
  File "C:\Users\MOISA\PycharmProjects\inss2\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 394, in find_element_by_xpath
    return self.find_element(by=By.XPATH, value=xpath)
  File "C:\Users\MOISA\PycharmProjects\inss2\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 978, in find_element
    'value': value})['value']
  File "C:\Users\MOISA\PycharmProjects\inss2\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "C:\Users\MOISA\PycharmProjects\inss2\venv\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: /html/body/main[1]/div[1]/div[1]/div[1]/div[1]/h2

这是search_cpfs:

def search_cpfs(self):
    nomes = []
    idades = []
    beneficios = []
    concessoes = []
    salarios = []
    bancoss = []
    bancoscard = []
    consigs = []
    cards = []

    for cpf in self.cpfs:
        print(f"Procurando {cpf}.")

        self.driver.get(self.bot_url)

        cpf_input = self.driver.find_element_by_xpath('//*[@id="search"]/div/div[1]/input')
        cpf_input.send_keys(cpf)

        time.sleep(2)

        cpfButton = self.driver.find_element_by_xpath('//*[@id="search"]/div/div[2]/button')
        cpfButton.click()

        time.sleep(2)

        self.delay = 3  # seconds

        nome = self.driver.find_element_by_xpath("/html/body/main[1]/div[1]/div[1]/div[1]/div[1]/h2").text
        idade = self.driver.find_element_by_xpath("/html/body/main[1]/div[1]/div[1]/div[1]/div[1]/ul/li[2]").text
        age = re.search(r'\((.*?)Anos', idade).group(1)
        beneficio = self.driver.find_element_by_xpath(
            "/html/body/main[1]/div[1]/div[1]/div[1]/div[2]/div[5]/span/b").text
        concessao = self.driver.find_element_by_xpath("/html/body/main[1]/div[1]/div[1]/div[1]/div[2]/div[2]/span").text
        salario = self.driver.find_element_by_xpath(
            "/html/body/main[1]/div[1]/div[2]/div/div[3]/div[1]/div[1]/span").text
        bancos = self.driver.find_element_by_xpath('//*[@id="loans"]').text
        bancosw = re.findall(r'(?<=Banco )(\w+)', bancos)
        bankslist = ', '.join(bancosw)
        bancocard = self.driver.find_element_by_xpath('//*[@id="cards"]').text
        bcardw = re.findall(r'(?<=Banco )(\w+)', bancocard)
        bcardlist = ', '.join(bcardw)
        consig = self.driver.find_element_by_xpath("/html/body/main[1]/div[1]/div[1]/div[3]/div[2]/span").text
        card = self.driver.find_element_by_xpath("/html/body/main[1]/div[1]/div[1]/div[3]/div[3]/span").text

        try:
            WebDriverWait(self.driver, self.delay).until(
                EC.presence_of_element_located((By.XPATH, '//*[@id="main"]/div[1]/h2')))
            print('CPF Valido')

            print(nome, age, beneficio, concessao, salario, bankslist, bcardlist, consig, card)

        except NoSuchElementException:
            print('CPF Invalido')
            continue

        nomes.append(nome)
        idades.append(age)
        beneficios.append(beneficio)
        concessoes.append(concessao)
        salarios.append(salario)
        bancoss.append(bankslist)
        bancoscard.append(bcardlist)
        consigs.append(consig)
        cards.append(card)

    return nomes, idades, beneficios, concessoes, salarios, bancoss, bancoscard, consigs, cards

页面是这样的:

1- 如果客户端代码正常,页面重定向并显示一些我已经可以抓取的信息;

2-如果客户端代码没有所有号码,"search"按钮什么都不做;

3-如果客户端代码有所有数字但有问题,页面会弹出。

错误在 bot_url.search_cpfs() 中出现,因此您需要将该调用移到 try except 中。你的情况:

def process_cpf_list(self):
    cpfs = self.sheet.col_values(self.cpf_col)[1:]

    bot_url = BOT(cpfs)

    try:
        # This is where the error is raised
        nomes, idades, beneficios, concessoes, salarios, bancoss, bancoscard, consigs, cards = bot_url.search_cpfs()
        print("Atualizando...")

        for i in range(len(nomes)):
            # You may want to add a different error handler here
            self.sheet.update_cell(i + 2, self.nome_col, nomes[i])
            self.sheet.update_cell(i + 2, self.age_col, idades[i])
            self.sheet.update_cell(i + 2, self.beneficio_col, beneficios[i])
            self.sheet.update_cell(i + 2, self.concessao_col, concessoes[i])
            self.sheet.update_cell(i + 2, self.salario_col, salarios[i])
            self.sheet.update_cell(i + 2, self.bancos_col, bancoss[i])
            self.sheet.update_cell(i + 2, self.bancocard_col, bancoscard[i])
            self.sheet.update_cell(i + 2, self.consig_col, consigs[i])
            self.sheet.update_cell(i + 2, self.card_col, cards[i])
    except NoSuchElementException:
        print('CPF Invalido')
        pass

更新

在您的 search_cpfs 方法中,您只需将所有 find_element_by_xpath 行包装在 try 和 except:

# def search_cpfs()
# ....
for cpf in self.cpfs:
    print(f"Procurando {cpf}.")

    self.driver.get(self.bot_url)

    try:
        cpf_input = self.driver.find_element_by_xpath('//*[@id="search"]/div/div[1]/input')
        cpf_input.send_keys(cpf)

        time.sleep(2)

        cpfButton = self.driver.find_element_by_xpath('//*[@id="search"]/div/div[2]/button')
        cpfButton.click()

        time.sleep(2)

        self.delay = 3  # seconds

        nome = self.driver.find_element_by_xpath("/html/body/main[1]/div[1]/div[1]/div[1]/div[1]/h2").text
        idade = self.driver.find_element_by_xpath("/html/body/main[1]/div[1]/div[1]/div[1]/div[1]/ul/li[2]").text
        age = re.search(r'\((.*?)Anos', idade).group(1)
        beneficio = self.driver.find_element_by_xpath(
            "/html/body/main[1]/div[1]/div[1]/div[1]/div[2]/div[5]/span/b").text
        concessao = self.driver.find_element_by_xpath("/html/body/main[1]/div[1]/div[1]/div[1]/div[2]/div[2]/span").text
        salario = self.driver.find_element_by_xpath(
            "/html/body/main[1]/div[1]/div[2]/div/div[3]/div[1]/div[1]/span").text
        bancos = self.driver.find_element_by_xpath('//*[@id="loans"]').text
        bancosw = re.findall(r'(?<=Banco )(\w+)', bancos)
        bankslist = ', '.join(bancosw)
        bancocard = self.driver.find_element_by_xpath('//*[@id="cards"]').text
        bcardw = re.findall(r'(?<=Banco )(\w+)', bancocard)
        bcardlist = ', '.join(bcardw)
        consig = self.driver.find_element_by_xpath("/html/body/main[1]/div[1]/div[1]/div[3]/div[2]/span").text
        card = self.driver.find_element_by_xpath("/html/body/main[1]/div[1]/div[1]/div[3]/div[3]/span").text

        WebDriverWait(self.driver, self.delay).until(
                EC.presence_of_element_located((By.XPATH, '//*[@id="main"]/div[1]/h2')))
        print('CPF Valido**)

        print(nome, age, beneficio, concessao, salario, bankslist, bcardlist, consig, card)

    except NoSuchElementException:
        print('CPF Invalido')
        continue

nomes.append(nome)
idades.append(age)
beneficios.append(benefici

更新 2*

顺便说一句,在你的问题中,引发错误的是这一行:

nome = self.driver.find_element_by_xpath("/html/body/main[1]/div[1]/div[1]/div[1]/div[1]/h2").text

因此,如果您确定所有其他行都不会引发错误,则可以将该行包装在 try except 中,而不是包含所有其他行,我只是在下面对其进行了简化:

for cpf in self.cpfs:
    # other codes here
    # ....
    cpf_input = self.driver.find_element_by_xpath('//*[@id="search"]/div/div[1]/input')
    cpf_input.send_keys(cpf)

    # other codes here
    # ....

    try:
        # This is the line that raises the error, so you can wrap this line only
        # But to be safe, you can follow the previous one
        nome = self.driver.find_element_by_xpath("/html/body/main[1]/div[1]/div[1]/div[1]/div[1]/h2").text
    except NoSuchElementException:
        print('CPF Invalido')
        continue

    # other code follows...


nomes.append(nome)
idades.append(age)
beneficios.append(benefici