有人能帮我写这段代码吗
我正在努力实现这一目标,但我在完成这一部分时遇到了一点困难:
driver.find_element_by_id("Cpf").send_keys(sheet.cell(row=Count, column=2).value, Keys.RETURN)
results = wait.until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "table[class*='table table-striped table-bordered dataTable'] > tbody > tr[class*=odd]")))
resultado_cnpc = results[0].text.strip() if "EmptyDataRow" in results[0].get_attribute("class") else results[0].find_element_by_xpath("./td[1]").text.strip()
resultado_nome = results[0].text.strip() if "EmptyDataRow" in results[0].get_attribute("class") else results[0].find_element_by_xpath("./td[2]").text.strip()
resultado_registro = results[0].text.strip() if "EmptyDataRow" in results[0].get_attribute("class") else results[0].find_element_by_xpath("./td[3]").text.strip()
resultado_uf = results[0].text.strip() if "EmptyDataRow" in results[0].get_attribute("class") else results[0].find_element_by_xpath("./td[4]").text.strip()
resultado_inclusao = results[0].text.strip() if "EmptyDataRow" in results[0].get_attribute("class") else results[0].find_element_by_xpath("./td[5]").text.strip()
进入此网页:http://www1.cfc.org.br/sisweb/Registro/ConsultaCNPC 在第二个框中显示此数据:336.174.128-90
我得到了这个错误:
NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"./td[2]"}
我对python还是新手
看起来
./td[2]
在<tr class='odd'>
下只有一个td
元素的情况下抛出了NoSuchElementException
。如果表中没有结果,则会发生这种情况这可以通过在调用
driver.find_element_by_xpath("./td[2]")
之前检查子元素的计数来解决。我将重构这段代码,以便更清楚地了解有搜索结果与没有搜索结果的场景另外,我注意到一些搜索结果显示
<tr class='odd'>
和其他<tr class='even'>
。我不确定您是否打算排除even
类行,因此我将为这两个行提供一个示例下面的示例使用“CPF”字段进行搜索,然后等待结果行出现。代码在结果行中循环并打印出单元格文本。如果表中没有结果,循环将中断
我运行的测试的输出:
要获取第一行的所有列,可以使用
//table[@id='table-cnpc']//tr[1]//td[not(@class='dataTables_empty')]
xpath。此xpath还处理空结果相关问题 更多 >
编程相关推荐