无论我做什么都无法选择硒元素

时间:2019-01-23 20:18:53

标签: python selenium webdriver

我正在尝试使用硒开发刮板,但无法在以下页面中选择元素:

http://comprasnet.gov.br/acesso.asp?url=/ConsultaLicitacoes/ConsLicitacao_texto.asp

我要获取的元素是搜索栏“ Texto / Termos a serem pesquisados”

我尝试过

element = driver.find_element_by_id("txtTermo")

element = driver.find_element_by_name("txtTermo")

我还尝试了xpath和CSS选择器。

我的代码:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Chrome()
driver.get("http://comprasnet.gov.br/acesso.asp?url=/ConsultaLicitacoes/ConsLicitacao_texto.asp")

我希望我可以获取元素,以便发送密钥。

但是我收到以下错误:

  

selenium.common.exceptions.NoSuchElementException:消息:没有这样的消息   元素:无法找到元素:   {“方法”:“名称”,“选择器”:“ txtTermo”}(会话信息:   chrome = 71.0.3578.98)(驱动程序信息:chromedriver = 2.45.615279   (12b89733300bd268cff3b78fc76cb8f3a7cc44e5),平台= Linux   4.15.0-43-通用x86_64)

1 个答案:

答案 0 :(得分:2)

您尝试获取的元素在框架内。框架是它们自己的文档,被Selenium视为单独的搜索上下文:

>>> from selenium import webdriver
>>> driver = webdriver.Chrome()
>>> driver.get("http://comprasnet.gov.br/acesso.asp?url=/ConsultaLicitacoes/ConsLicitacao_texto.asp")
>>> element = driver.find_element_by_id("txtTermo")
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    element = driver.find_element_by_id("txtTermo")
  File "#PATH_REDACTED#\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 360, in find_element_by_id
    return self.find_element(by=By.ID, value=id_)
  File "#PATH_REDACTED#\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 978, in find_element
    'value': value})['value']
  File "#PATH_REDACTED#\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "#PATH_REDACTED#\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"id","selector":"txtTermo"}
  (Session info: chrome=71.0.3578.98)
  (Driver info: chromedriver=2.45.615291 (ec3682e3c9061c10f26ea9e5cdcf3c53f3f74387),platform=Windows NT 10.0.15063 x86_64)

>>> driver.switch_to.frame('main2')
>>> element = driver.find_element_by_id("txtTermo")
>>> element
<selenium.webdriver.remote.webelement.WebElement (session="d5a30c9f45d49a23152767da0b811f58", element="0.6642244007973428-1")>

考虑一下您可以浏览的框架层次结构,每个框架包含它们自己的完整DOM层次结构。在框架内完成工作后,如果要返回顶层文档并做更多工作,请切换到默认内容:

driver.switch_to.default_content()

如今,不鼓励使用框架,您不太可能在较新的应用程序中遇到这些框架,但是在过去,我发现(听起来很愚蠢)检查driver.page_source的值可以帮助您了解当前正在处理的整个文档的哪一部分。这样只会显示当前搜索上下文的来源,即您当前切换到的框架。