如何在Angular网站上查找用于搜索的Xpath

2024-09-29 00:17:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用python在angular网站上进行自动搜索。在通过Xpath成功测试了简单Google搜索的搜索字段标识之后,我很难找到以下html的正确Xpath蓝色的html行,我希望在这个website

enter image description here

全文如下:

<div class="input-group">
      <input autofocus="" class="form-control ng-pristine ng-valid ng-touched" formcontrolname="term" type="search" placeholder="Suchen">
    </div>

我使用WebDriverWaitfind_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()

为什么这些都不起作用?什么有效?为什么


Tags: divforminputbydriverelementfindng
2条回答

固定代码:

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, 20).until(EC.element_to_be_clickable((By.XPATH,search_button_locator)))
driver.find_element_by_xpath(search_button_locator).click()

你的错误:

  1. @class='form-control auto-complete ng-pristine ng-valid ng-valid-editable ng-empty ng-touched'-对类使用严格比较是一种不好的做法,因为它变化太频繁。让我们使用这样的东西//*[contains(@class, 'one_class_name')]
  2. 错误的定位器//div[text()='Suchen'],正确://button[text()='Suchen']

要开始,请确保您正在使用Chrome浏览器。查看源代码时,右键单击元素(在本例中为<input>标记,然后执行Copy>;Copy XPath

screen shot of how to select the XPath within Chrome browser

相关问题 更多 >