[英]How to select an option from the auto suggestions using Selenium and Python
I'm trying to select an option from the auto-suggestions after sending a text within the search field of the Selenium documentation website.在Selenium 文档网站的搜索字段中发送文本后,我正在尝试 select 自动建议中的一个选项。 But I'm unable to find any of those suggestions.
但我找不到任何这些建议。
Code trials:代码试验:
driver.get('https://www.selenium.dev/documentation/en/')
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#search-by"))).send_keys("selenium")
Snapshot of the auto-suggestions:自动建议的快照:
Can anyone help me out please to select any of the auto-suggestions?任何人都可以帮助我 select 任何自动建议吗?
The autocomplete-suggestions
is the div
that holds all the autocomplete-suggestion
's. autocomplete-suggestions
是包含所有autocomplete-suggestion
的div
。
Here is a snip of the elements这是元素的片段
To capture the elements I used the f8
button when searching for selenium, that way the elements don't disappear.为了捕捉元素,我在搜索 selenium 时使用了
f8
按钮,这样元素就不会消失。
Here is a code snip for visualization:这是可视化的代码片段:
def highlight_element(element):
driver_elem = element.parent
def apply_style(s):
driver_elem.execute_script("arguments[0].setAttribute('style', arguments[1]);",
element, s)
original_style = element.get_attribute('style')
apply_style("background: yellow; border: 2px solid red;")
sleep(0.5)
apply_style(original_style)
driver.get("https://www.selenium.dev/documentation/en/")
WebDriverWait(driver,30).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#search-by")))
driver.find_element_by_css_selector("#search-by").send_keys("selenium")
WebDriverWait(driver,30).until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, ".autocomplete-suggestions .autocomplete-suggestion")))
for ele in driver.find_elements_by_css_selector(".autocomplete-suggestions .autocomplete-suggestion"):
highlight_element(ele)
+1 for @Moshe Slavin's answer. +1 @Moshe Slavin 的回答。 The
autocomplete-suggestions
is the div that holds all the autocomplete-suggestion's
autocomplete-suggestions
是包含所有autocomplete-suggestion's
的 div
In order to capture the elements, I used the getPageSource()
to print out the elements in the page.为了捕获元素,我使用
getPageSource()
打印出页面中的元素。
And once I figured out the element the rest of the code below is self explanatory一旦我弄清楚了下面代码的 rest 元素,就可以自我解释
wait.until(ExpectedConditions.elementToBeClickable(By.className("autocomplete-suggestion")));
List<WebElement> abc = driver.findElements(By.className("autocomplete-suggestion"));
String value = "Remote WebDriver client";
List<String> def = new ArrayList<String>();
for (int i = 0; i < abc.size(); i++) {
//Get the values and store it in a list
def.add(abc.get(i).getAttribute("data-title"));
}
if (def.contains(value))
abc.get(def.indexOf(value)).click();
else
System.out.println("Value not present");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.