You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Selenium无法定位元素求助:PGMEI网站爬取问题

问题:Selenium定位"Emitir Guia de pagamento (DAS)"元素失败

输入CNPJ后,点击该链接时触发如下错误:

Message: no such element: Unable to locate element: {"method":"css selector","selector":"navbarCollapse > ul:nth-child(1) > li:nth-child(2) > a"}
(Session info: chrome=120.0.6099.225)

错误原因

  1. CSS选择器错误:目标元素所在容器navbarCollapse是id属性,CSS选择器中id需以#开头,原代码缺少#导致无法匹配元素。
  2. 等待逻辑不合理:固定时长sleep无法保证页面元素完全渲染,可能在元素未加载完成时就执行定位操作。

解决方案

1. 修正元素定位方式

可以采用以下更可靠的定位方式替代原错误的CSS选择器:

  • 按链接文本定位:By.LINK_TEXT, "Emitir Guia de Pagamento (DAS)"
  • 按href属性定位:By.CSS_SELECTOR, 'a[href="/SimplesNacional/Aplicacoes/ATSPO/pgmei.app/emissao"]'
  • 修正后的CSS选择器:#navbarCollapse > ul.nav.navbar-nav > li:nth-child(2) > a

2. 用显式等待替代固定sleep

显式等待会等待元素满足可操作条件后再执行代码,比固定sleep更稳定,需导入WebDriverWait和expected_conditions模块。

修正后的完整代码

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.select import Select

driver = webdriver.Chrome()
wait = WebDriverWait(driver, 10)  # 设置最长等待时长10秒

# 访问目标页面
driver.get("https://www8.receita.fazenda.gov.br/simplesnacional/aplicacoes/atspo/pgmei.app/identificacao")

# 输入CNPJ
cnpj = wait.until(EC.presence_of_element_located((By.NAME, 'cnpj')))
cnpj.send_keys('00080303000111')

# 点击"Emitir Guia de Pagamento (DAS)"链接
button_das = wait.until(EC.element_to_be_clickable((By.LINK_TEXT, "Emitir Guia de Pagamento (DAS)")))
button_das.click()

# 选择日历年度
select_calendar = wait.until(EC.presence_of_element_located((By.NAME, 'anoCalendarioSelect')))
select = Select(select_calendar)
select.select_by_value('2023')

# 点击确认按钮
button_calendar = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, 'body > div > section:nth-child(4) > div > div > div > div > div > div > form > button')))
button_calendar.click()

# 输入付款日期
dtpagamento = wait.until(EC.presence_of_element_located((By.NAME, 'dataPagamentoInformada')))
dtpagamento.send_keys('24/01/2024')

# 点击生成DAS按钮
button_gerarDas = wait.until(EC.element_to_be_clickable((By.ID, 'btnEmitirDas')))
button_gerarDas.click()

# 操作完成后可关闭浏览器
# driver.quit()

内容的提问来源于stack exchange,提问作者Ruama

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 17:37:35