问题描述
我想使用python在有角度的网站上进行自动搜索。在通过简单的Google搜索成功通过Xpath测试了搜索字段的标识之后,我很难找到以下html的正确Xpath。 我想在此website
上使用Xpath的html行为蓝色为文本:
<div class="input-group">
<input autofocus="" class="form-control ng-pristine ng-valid ng-touched" formcontrolname="term" type="search" placeholder="Suchen">
</div>
我使用webdriverwait
和find_element_by_xpath
尝试了以下(以及更多):
webdriverwait(driver,20).until(EC.element_to_be_clickable((By.XPATH,"//input[@class='form-control auto-complete ng-pristine ng-valid ng-valid-editable ng-empty ng-touched' and @type='search']")))
element = driver.find_element_by_xpath('//input[@placeholder="Suchen"]').send_keys('AYT')
element = driver.find_element_by_xpath("//input[class='form-control ng-pristine ng-valid ng-touched']")
element = driver.find_element_by_xpath("Xpath=//div[text()='Suchen']").click()
为什么这些都不起作用?什么有效,为什么?
解决方法
固定代码:
search_input_locator = "//input[@placeholder='Suchen']"
search_button_locator = "//button[text()='Suchen']"
WebDriverWait(driver,20).until(EC.element_to_be_clickable((By.XPATH,search_input_locator)))
driver.find_element_by_xpath(search_input_locator).send_keys('AYT')
WebDriverWait(driver,search_button_locator)))
driver.find_element_by_xpath(search_button_locator).click()
您的错误:
-
@class='form-control auto-complete ng-pristine ng-valid ng-valid-editable ng-empty ng-touched'
-对类使用严格比较是一种不好的做法,因为它经常更改。让我们使用类似//*[contains(@class,'one_class_name')]
的方式
- 定位器
//div[text()='Suchen']
错误,正确://button[text()='Suchen']
要开始,请确保您使用的是Chrome浏览器。在查看源代码时,右键单击该元素(在本例中为<input>
标签,然后执行Copy> Copy XPath。