Skip to content

Commit

Permalink
Find element by xpath (mattsse#162)
Browse files Browse the repository at this point in the history
* find element or elements using xpath query

* revert workspace ignore

* revert
  • Loading branch information
AlexStorm1313 authored Jul 22, 2023
1 parent 6264e0a commit bdac44c
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 1 deletion.
30 changes: 29 additions & 1 deletion src/handler/page.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ use futures::{SinkExt, StreamExt};

use chromiumoxide_cdp::cdp::browser_protocol::browser::{GetVersionParams, GetVersionReturns};
use chromiumoxide_cdp::cdp::browser_protocol::dom::{
NodeId, QuerySelectorAllParams, QuerySelectorParams, Rgba,
DiscardSearchResultsParams, GetSearchResultsParams, NodeId, PerformSearchParams,
QuerySelectorAllParams, QuerySelectorParams, Rgba,
};
use chromiumoxide_cdp::cdp::browser_protocol::emulation::{
ClearDeviceMetricsOverrideParams, SetDefaultBackgroundColorOverrideParams,
Expand Down Expand Up @@ -143,6 +144,33 @@ impl PageInner {
.node_ids)
}

/// Returns all elements which matches the given xpath selector
pub async fn find_xpaths(&self, query: impl Into<String>) -> Result<Vec<NodeId>> {
let perform_search_returns = self
.execute(PerformSearchParams {
query: query.into(),
include_user_agent_shadow_dom: Some(true),
})
.await?
.result;

let search_results = self
.execute(GetSearchResultsParams::new(
perform_search_returns.search_id.clone(),
0,
perform_search_returns.result_count,
))
.await?
.result;

self.execute(DiscardSearchResultsParams::new(
perform_search_returns.search_id,
))
.await?;

Ok(search_results.node_ids)
}

/// Moves the mouse to this point (dispatches a mouseMoved event)
pub async fn move_mouse(&self, point: Point) -> Result<&Self> {
self.execute(DispatchMouseEventParams::new(
Expand Down
17 changes: 17 additions & 0 deletions src/page.rs
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,23 @@ impl Page {
Element::from_nodes(&self.inner, &node_ids).await
}

/// Returns the first element in the document which matches the given xpath
/// selector.
///
/// Execute a xpath selector on the document's node.
pub async fn find_xpath(&self, selector: impl Into<String>) -> Result<Element> {
self.get_document().await?;
let node_id = self.inner.find_xpaths(selector).await?[0];
Element::new(Arc::clone(&self.inner), node_id).await
}

/// Return all `Element`s in the document that match the given xpath selector
pub async fn find_xpaths(&self, selector: impl Into<String>) -> Result<Vec<Element>> {
self.get_document().await?;
let node_ids = self.inner.find_xpaths(selector).await?;
Element::from_nodes(&self.inner, &node_ids).await
}

/// Describes node given its id
pub async fn describe_node(&self, node_id: NodeId) -> Result<Node> {
let resp = self
Expand Down

0 comments on commit bdac44c

Please sign in to comment.