我必须将字符串发送到网页中的文本字段。 我试图通过xpath访问它,但是每次我新打开网页时,xpath都会不断变化。因此,我决定使用类名或标签名来访问它。但是我收到一个错误,提示密钥无法传递到访问字段。
网页中文本文件的HTML:
<div class = "SearchBox">
<input aria-label = 'xyz' placeholder = 'abc'>
</div>
我尝试了以下几行代码,但都没有用:
text = driver.find_element_by_xpath('//div[contains(@class,'SearchBox')] and input[contains(@aria-label,'xyz')]')
text = driver.find_element_by_class_name('SearchBox')
text = driver.find_element_by_xpath("//div[@class='SearchBox']/input")
text = driver.find_element_by_xpath("//div[@class='SearchBox']/input[contains(@aria-label,'Combobox expanded. Use arrow keys to select available options or type to search.') and @dojoattachpoint='_searchInput']")
我在做什么错?请帮助。
错误日志:
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
l.send_keys("abcdef")
File "C:\Users\Pavan-Kumar\AppData\Local\Programs\Python\Python35\lib\site-packages\selenium\webdriver\remote\webelement.py", line 479, in send_keys
'value': keys_to_typing(value)})
File "C:\Users\Pavan-Kumar\AppData\Local\Programs\Python\Python35\lib\site-packages\selenium\webdriver\remote\webelement.py", line 628, in _execute
return self._parent.execute(command, params)
File "C:\Users\Pavan-Kumar\AppData\Local\Programs\Python\Python35\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 314, in execute
self.error_handler.check_response(response)
File "C:\Users\Pavan-Kumar\AppData\Local\Programs\Python\Python35\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.ElementNotVisibleException: Message: element not visible
(Session info: chrome=65.0.3325.146)
(Driver info: chromedriver=2.38.552522 (437e6fbedfa8762dec75e2c5b3ddb86763dc9dcb),platform=Windows NT 10.0.17134 x86_64)
HTML代码图片:
答案 0 :(得分:2)
您编写的xpath包含div标签和输入标签的标识符。 Selenium将如何理解您正在尝试访问输入字段! 如果您尝试将div标签用作锚点来到达输入标签,则xpath应该看起来像这样... // div [@ class ='SearchBox'] / input
答案 1 :(得分:1)
下面的xpath应该可以根据您共享的html结构图像为您提供帮助。
//div[@class='SearchBox']/input[contains(@aria-label,'expanded') and @dojoattachpoint='_searchInput']