pub struct Element<'a> {
pub remote_object_id: String,
pub backend_node_id: NodeId,
pub node_id: NodeId,
pub parent: &'a Tab,
pub attrs: HashMap<String, String>,
}
Expand description
A handle to a DOM Element.
Typically you get access to these by passing Tab.wait_for_element
a CSS selector. Once
you have a handle to an element, you can click it, type into it, inspect its
attributes, and more. You can even run a JavaScript function inside the tab which can reference
the element via this
.
Fields§
§remote_object_id: String
§backend_node_id: NodeId
§node_id: NodeId
§parent: &'a Tab
§attrs: HashMap<String, String>
Implementations§
source§impl<'a> Element<'a>
impl<'a> Element<'a>
sourcepub fn new(parent: &'a Tab, node_id: NodeId) -> Result<Self>
pub fn new(parent: &'a Tab, node_id: NodeId) -> Result<Self>
Using a ‘node_id’, of the type returned by QuerySelector and QuerySelectorAll, this finds the ‘backend_node_id’ and ‘remote_object_id’ which are stable identifiers, unlike node_id. We use these two when making various calls to the API because of that.
Examples found in repository?
728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869
pub fn find_element_by_xpath(&self, query: &str) -> Result<Element<'_>> {
//self.get_document()?;
self.call_method(DOM::PerformSearch {
query: query.to_string(),
include_user_agent_shadow_dom: None,
})
.and_then(|o| {
Ok(self
.call_method(DOM::GetSearchResults {
search_id: o.search_id,
from_index: 0,
to_index: o.result_count,
})?
.node_ids[0])
})
.and_then(|id| {
if id == 0 {
Err(NoElementFound {}.into())
} else {
Ok(Element::new(&self, id)?)
}
})
}
pub fn run_query_selector_on_node(
&self,
node_id: NodeId,
selector: &str,
) -> Result<Element<'_>> {
let node_id = self
.call_method(DOM::QuerySelector {
node_id,
selector: selector.to_string(),
})
.map_err(NoElementFound::map)?
.node_id;
Element::new(&self, node_id)
}
pub fn run_query_selector_all_on_node(
&self,
node_id: NodeId,
selector: &str,
) -> Result<Vec<Element<'_>>> {
let node_ids = self
.call_method(DOM::QuerySelectorAll {
node_id,
selector: selector.to_string(),
})
.map_err(NoElementFound::map)?
.node_ids;
node_ids
.iter()
.map(|node_id| Element::new(&self, *node_id))
.collect()
}
pub fn get_document(&self) -> Result<Node> {
Ok(self
.call_method(DOM::GetDocument {
depth: Some(0),
pierce: Some(false),
})?
.root)
}
/// Get the full HTML contents of the page.
pub fn get_content(&self) -> Result<String> {
let func = "
(function () {
let retVal = '';
if (document.doctype)
retVal = new XMLSerializer().serializeToString(document.doctype);
if (document.documentElement)
retVal += document.documentElement.outerHTML;
return retVal;
})();";
let html = self
.evaluate(func, false)?
.value
.unwrap();
Ok(String::from(html.as_str().unwrap()))
}
pub fn get_page_origin(&self) -> Result<String> {
let func = "
(function () {
return window.location.origin;
})();";
let html = self
.evaluate(func, false)?
.value
.unwrap();
Ok(String::from(html.as_str().unwrap()))
}
pub fn find_elements(&self, selector: &str) -> Result<Vec<Element<'_>>> {
trace!("Looking up elements via selector: {}", selector);
let root_node_id = self.document.lock().unwrap().as_ref().unwrap().node_id; // self.get_document()?.node_id;
let node_ids = self
.call_method(DOM::QuerySelectorAll {
node_id: root_node_id,
selector: selector.to_string(),
})
.map_err(NoElementFound::map)?
.node_ids;
if node_ids.is_empty() {
return Err(NoElementFound {}.into());
}
node_ids
.into_iter()
.map(|node_id| Element::new(&self, node_id))
.collect()
}
pub fn find_elements_by_xpath(&self, query: &str) -> Result<Vec<Element<'_>>> {
self.call_method(DOM::PerformSearch {
query: query.to_string(),
include_user_agent_shadow_dom: None,
})
.and_then(|o| {
Ok(self
.call_method(DOM::GetSearchResults {
search_id: o.search_id,
from_index: 0,
to_index: o.result_count,
})?
.node_ids)
})
.and_then(|ids| {
ids.iter()
.filter(|id| **id != 0)
.map(|id| Element::new(self, *id))
.collect()
})
}
More examples
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
pub fn find_element_by_xpath(&self, query: &str) -> Result<Element<'_>> {
self.parent.get_document()?;
self.parent
.call_method(DOM::PerformSearch {
query: query.to_string(),
include_user_agent_shadow_dom: Some(true),
})
.and_then(|o| {
Ok(self
.parent
.call_method(DOM::GetSearchResults {
search_id: o.search_id,
from_index: 0,
to_index: o.result_count,
})?
.node_ids[0])
})
.and_then(|id| {
if id == 0 {
Err(NoElementFound {}.into())
} else {
Ok(Element::new(self.parent, id)?)
}
})
}
/// Returns the first element in the document which matches the given CSS selector.
///
/// Equivalent to the following JS:
///
/// ```js
/// document.querySelector(selector)
/// ```
///
/// ```rust
/// # use anyhow::Result;
/// # // Awful hack to get access to testing utils common between integration, doctest, and unit tests
/// # mod server {
/// # include!("../../../testing_utils/server.rs");
/// # }
/// # fn main() -> Result<()> {
/// #
/// use headless_chrome::Browser;
///
/// let browser = Browser::default()?;
/// let initial_tab = browser.wait_for_initial_tab()?;
///
/// let file_server = server::Server::with_dumb_html(include_str!("../../../../tests/simple.html"));
/// let containing_element = initial_tab.navigate_to(&file_server.url())?
/// .wait_until_navigated()?
/// .find_element("div#position-test")?;
/// let inner_divs = containing_element.find_elements("div")?;
/// assert_eq!(inner_divs.len(), 5);
/// #
/// # Ok(())
/// # }
/// ```
pub fn find_elements(&self, selector: &str) -> Result<Vec<Self>> {
self.parent
.run_query_selector_all_on_node(self.node_id, selector)
}
pub fn find_elements_by_xpath(&self, query: &str) -> Result<Vec<Element<'_>>> {
self.parent.get_document()?;
self.parent
.call_method(DOM::PerformSearch {
query: query.to_string(),
include_user_agent_shadow_dom: Some(true),
})
.and_then(|o| {
Ok(self
.parent
.call_method(DOM::GetSearchResults {
search_id: o.search_id,
from_index: 0,
to_index: o.result_count,
})?
.node_ids)
})
.and_then(|ids| {
ids.iter()
.filter(|id| **id != 0)
.map(|id| Element::new(self.parent, *id))
.collect()
})
}
sourcepub fn find_element(&self, selector: &str) -> Result<Self>
pub fn find_element(&self, selector: &str) -> Result<Self>
Returns the first element in the document which matches the given CSS selector.
Equivalent to the following JS:
document.querySelector(selector)
use headless_chrome::Browser;
let browser = Browser::default()?;
let initial_tab = browser.wait_for_initial_tab()?;
let file_server = server::Server::with_dumb_html(include_str!("../../../../tests/simple.html"));
let containing_element = initial_tab.navigate_to(&file_server.url())?
.wait_until_navigated()?
.find_element("div#position-test")?;
let inner_element = containing_element.find_element("#strictly-above")?;
let attrs = inner_element.get_attributes()?.unwrap();
assert_eq!(attrs["id"], "strictly-above");
sourcepub fn find_element_by_xpath(&self, query: &str) -> Result<Element<'_>>
pub fn find_element_by_xpath(&self, query: &str) -> Result<Element<'_>>
sourcepub fn find_elements(&self, selector: &str) -> Result<Vec<Self>>
pub fn find_elements(&self, selector: &str) -> Result<Vec<Self>>
Returns the first element in the document which matches the given CSS selector.
Equivalent to the following JS:
document.querySelector(selector)
use headless_chrome::Browser;
let browser = Browser::default()?;
let initial_tab = browser.wait_for_initial_tab()?;
let file_server = server::Server::with_dumb_html(include_str!("../../../../tests/simple.html"));
let containing_element = initial_tab.navigate_to(&file_server.url())?
.wait_until_navigated()?
.find_element("div#position-test")?;
let inner_divs = containing_element.find_elements("div")?;
assert_eq!(inner_divs.len(), 5);
pub fn wait_for_element(&self, selector: &str) -> Result<Element<'_>>
pub fn wait_for_xpath(&self, selector: &str) -> Result<Element<'_>>
sourcepub fn wait_for_element_with_custom_timeout(
&self,
selector: &str,
timeout: Duration
) -> Result<Element<'_>>
pub fn wait_for_element_with_custom_timeout(
&self,
selector: &str,
timeout: Duration
) -> Result<Element<'_>>
sourcepub fn wait_for_xpath_with_custom_timeout(
&self,
selector: &str,
timeout: Duration
) -> Result<Element<'_>>
pub fn wait_for_xpath_with_custom_timeout(
&self,
selector: &str,
timeout: Duration
) -> Result<Element<'_>>
pub fn wait_for_elements(&self, selector: &str) -> Result<Vec<Element<'_>>>
pub fn wait_for_elements_by_xpath(
&self,
selector: &str
) -> Result<Vec<Element<'_>>>
sourcepub fn move_mouse_over(&self) -> Result<&Self>
pub fn move_mouse_over(&self) -> Result<&Self>
Moves the mouse to the middle of this element
pub fn type_into(&self, text: &str) -> Result<&Self>
sourcepub fn call_js_fn(
&self,
function_declaration: &str,
args: Vec<Value>,
await_promise: bool
) -> Result<RemoteObject>
pub fn call_js_fn(
&self,
function_declaration: &str,
args: Vec<Value>,
await_promise: bool
) -> Result<RemoteObject>
Examples found in repository?
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620
pub fn click(&self) -> Result<&Self> {
self.scroll_into_view()?;
debug!("Clicking element {:?}", &self);
self.call_js_fn("function() { this.click(); return 1; }", vec![], false)?
.value.unwrap();
/* let midpoint = self.get_midpoint()?;
self.parent.click_point(midpoint)?; */
if let Err(_) = self.parent.wait_until_navigated() {
info!("[CLICK] Page load timeout..");
}
// MUST reload DOM in case page refreshed..
self.parent.load_document();
Ok(self)
}
pub fn type_into(&self, text: &str) -> Result<&Self> {
self.click()?;
debug!("Typing into element ( {:?} ): {}", &self, text);
self.parent.type_str(text)?;
Ok(self)
}
pub fn call_js_fn(
&self,
function_declaration: &str,
args: Vec<serde_json::Value>,
await_promise: bool,
) -> Result<Runtime::RemoteObject> {
let mut args = args.clone();
let result = self
.parent
.call_method(Runtime::CallFunctionOn {
object_id: Some(self.remote_object_id.clone()),
function_declaration: function_declaration.to_string(),
arguments: args
.iter_mut()
.map(|v| {
Some(Runtime::CallArgument {
value: Some(v.take()),
unserializable_value: None,
object_id: None,
})
})
.collect(),
return_by_value: Some(false),
generate_preview: Some(true),
silent: Some(false),
await_promise: Some(await_promise),
user_gesture: None,
execution_context_id: None,
object_group: None,
throw_on_side_effect: None,
})?
.result;
Ok(result)
}
pub fn focus(&self) -> Result<&Self> {
self.scroll_into_view()?;
self.parent.call_method(DOM::Focus {
backend_node_id: Some(self.backend_node_id),
node_id: None,
object_id: None,
})?;
Ok(self)
}
/// Returns the inner text of an HTML Element. Returns an empty string on elements with no text.
///
/// Note: .innerText and .textContent are not the same thing. See:
/// https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/innerText
///
/// Note: if you somehow call this on a node that's not an HTML Element (e.g. `document`), this
/// will fail.
/// ```rust
/// # use anyhow::Result;
/// # fn main() -> Result<()> {
/// #
/// use headless_chrome::Browser;
/// use std::time::Duration;
/// let browser = Browser::default()?;
/// let url = "https://web.archive.org/web/20190403224553/https://en.wikipedia.org/wiki/JavaScript";
/// let inner_text_content = browser.wait_for_initial_tab()?
/// .navigate_to(url)?
/// .wait_for_element_with_custom_timeout("#Misplaced_trust_in_developers", Duration::from_secs(10))?
/// .get_inner_text()?;
/// assert_eq!(inner_text_content, "Misplaced trust in developers");
/// #
/// # Ok(())
/// # }
/// ```
pub fn get_inner_text(&self) -> Result<String> {
let text: String = serde_json::from_value(
self.call_js_fn("function() { return this.innerText }", vec![], false)?
.value
.unwrap(),
)?;
Ok(text)
}
/// Get the full HTML contents of the element.
///
/// Equivalent to the following JS: ```element.outerHTML```.
pub fn get_content(&self) -> Result<String> {
let html = self.
call_js_fn("function() { return this.outerHTML }", vec![], false)?
.value
.unwrap();
Ok(String::from(html.as_str().unwrap()))
}
pub fn get_computed_styles(&self) -> Result<Vec<CSSComputedStyleProperty>> {
let styles = self
.parent
.call_method(CSS::GetComputedStyleForNode {
node_id: self.node_id,
})?
.computed_style;
Ok(styles)
}
pub fn get_description(&self) -> Result<DOM::Node> {
let node = self
.parent
.call_method(DOM::DescribeNode {
node_id: None,
backend_node_id: Some(self.backend_node_id),
depth: None,
object_id: None,
pierce: None,
})?
.node;
Ok(node)
}
/// Capture a screenshot of this element.
///
/// The screenshot is taken from the surface using this element's content-box.
///
/// ```rust,no_run
/// # use anyhow::Result;
/// # fn main() -> Result<()> {
/// #
/// use headless_chrome::{protocol::page::ScreenshotFormat, Browser};
/// let browser = Browser::default()?;
/// let png_data = browser.wait_for_initial_tab()?
/// .navigate_to("https://en.wikipedia.org/wiki/WebKit")?
/// .wait_for_element("#mw-content-text > div > table.infobox.vevent")?
/// .capture_screenshot(ScreenshotFormat::PNG)?;
/// #
/// # Ok(())
/// # }
/// ```
pub fn capture_screenshot(
&self,
format: Page::CaptureScreenshotFormatOption,
) -> Result<Vec<u8>> {
self.scroll_into_view()?;
self.parent.capture_screenshot(
format,
Some(90),
Some(self.get_box_model()?.content_viewport()),
true,
)
}
pub fn set_input_files(&self, file_paths: &[&str]) -> Result<&Self> {
self.parent.call_method(DOM::SetFileInputFiles {
files: file_paths.to_vec().iter().map(|v| v.to_string()).collect(),
backend_node_id: Some(self.backend_node_id),
node_id: None,
object_id: None,
})?;
Ok(self)
}
/// Scrolls the current element into view
///
/// Used prior to any action applied to the current element to ensure action is duable.
pub fn scroll_into_view(&self) -> Result<&Self> {
let result = self.call_js_fn(
"async function() {
if (!this.isConnected)
return 'Node is detached from document';
if (this.nodeType !== Node.ELEMENT_NODE)
return 'Node is not of type HTMLElement';
const visibleRatio = await new Promise(resolve => {
const observer = new IntersectionObserver(entries => {
resolve(entries[0].intersectionRatio);
observer.disconnect();
});
observer.observe(this);
});
if (visibleRatio !== 1.0)
this.scrollIntoView({
block: 'center',
inline: 'center',
behavior: 'instant'
});
return false;
}",
vec![],
true,
)?;
if result.Type == Runtime::RemoteObjectType::String {
let error_text = result.value.unwrap().as_str().unwrap().to_string();
return Err(ScrollFailed { error_text }.into());
}
Ok(self)
}
pub fn get_attributes(&self) -> Result<HashMap<String, String>> {
// https://chromedevtools.github.io/devtools-protocol/tot/DOM/#method-getAttributes
let mut attrs_map: HashMap<String, String> = HashMap::default();
/* let attrs = self.parent
.call_method(DOM::GetAttributes {
node_id: self.node_id
})?.attributes; */
let node = self.get_description().unwrap(); //.local_name;
let attrs = node.attributes.unwrap_or(vec![]);
let tag = node.local_name;
attrs_map.insert("tag".to_string(), tag);
attrs_map.insert("value".to_string(), node.value.unwrap_or("".to_string()));
for i in (0..attrs.len() - 1).step_by(2) {
let k = attrs[i].to_string();
let v = attrs[i+1].to_string();
attrs_map.insert(k, v);
}
Ok(attrs_map)
}
/* pub fn get_attributes(&self) -> Result<Option<Vec<String>>> {
let description = self.get_description()?;
Ok(description.attributes)
} */
/// Get boxes for this element
pub fn get_box_model(&self) -> Result<BoxModel> {
let model = self
.parent
.call_method(DOM::GetBoxModel {
node_id: None,
backend_node_id: Some(self.backend_node_id),
object_id: None,
})?
.model;
Ok(BoxModel {
content: ElementQuad::from_raw_points(&model.content),
padding: ElementQuad::from_raw_points(&model.padding),
border: ElementQuad::from_raw_points(&model.border),
margin: ElementQuad::from_raw_points(&model.margin),
width: model.width as f64,
height: model.height as f64,
})
}
pub fn get_midpoint(&self) -> Result<Point> {
match self
.parent
.call_method(DOM::GetContentQuads {
node_id: None,
backend_node_id: Some(self.backend_node_id),
object_id: None,
})
.and_then(|quad| {
let raw_quad = quad.quads.first().unwrap();
let input_quad = ElementQuad::from_raw_points(&raw_quad);
Ok((input_quad.bottom_right + input_quad.top_left) / 2.0)
}) {
Ok(e) => return Ok(e),
Err(_) => {
let mut p = Point { x: 0.0, y: 0.0 };
p = util::Wait::with_timeout(Duration::from_secs(20)).until(|| {
let r = self
.call_js_fn(
r#"
function() {
let rect = this.getBoundingClientRect();
if(rect.x != 0) {
this.scrollIntoView();
}
return this.getBoundingClientRect();
}
"#,
vec![],
false,
)
.unwrap();
let res = util::extract_midpoint(r);
match res {
Ok(v) => {
if v.x != 0.0 {
Some(v)
} else {
None
}
}
_ => None,
}
})?;
return Ok(p);
}
}
}
pub fn get_js_midpoint(&self) -> Result<Point> {
let result = self.call_js_fn(
"function(){return this.getBoundingClientRect(); }",
vec![],
false,
)?;
util::extract_midpoint(result)
}
pub fn focus(&self) -> Result<&Self>
sourcepub fn get_inner_text(&self) -> Result<String>
pub fn get_inner_text(&self) -> Result<String>
Returns the inner text of an HTML Element. Returns an empty string on elements with no text.
Note: .innerText and .textContent are not the same thing. See: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/innerText
Note: if you somehow call this on a node that’s not an HTML Element (e.g. document
), this
will fail.
use headless_chrome::Browser;
use std::time::Duration;
let browser = Browser::default()?;
let url = "https://web.archive.org/web/20190403224553/https://en.wikipedia.org/wiki/JavaScript";
let inner_text_content = browser.wait_for_initial_tab()?
.navigate_to(url)?
.wait_for_element_with_custom_timeout("#Misplaced_trust_in_developers", Duration::from_secs(10))?
.get_inner_text()?;
assert_eq!(inner_text_content, "Misplaced trust in developers");
sourcepub fn get_content(&self) -> Result<String>
pub fn get_content(&self) -> Result<String>
Get the full HTML contents of the element.
Equivalent to the following JS: element.outerHTML
.
pub fn get_computed_styles(&self) -> Result<Vec<CSSComputedStyleProperty>>
sourcepub fn get_description(&self) -> Result<Node>
pub fn get_description(&self) -> Result<Node>
Examples found in repository?
504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529
pub fn get_attributes(&self) -> Result<HashMap<String, String>> {
// https://chromedevtools.github.io/devtools-protocol/tot/DOM/#method-getAttributes
let mut attrs_map: HashMap<String, String> = HashMap::default();
/* let attrs = self.parent
.call_method(DOM::GetAttributes {
node_id: self.node_id
})?.attributes; */
let node = self.get_description().unwrap(); //.local_name;
let attrs = node.attributes.unwrap_or(vec![]);
let tag = node.local_name;
attrs_map.insert("tag".to_string(), tag);
attrs_map.insert("value".to_string(), node.value.unwrap_or("".to_string()));
for i in (0..attrs.len() - 1).step_by(2) {
let k = attrs[i].to_string();
let v = attrs[i+1].to_string();
attrs_map.insert(k, v);
}
Ok(attrs_map)
}
sourcepub fn capture_screenshot(
&self,
format: CaptureScreenshotFormatOption
) -> Result<Vec<u8>>
pub fn capture_screenshot(
&self,
format: CaptureScreenshotFormatOption
) -> Result<Vec<u8>>
Capture a screenshot of this element.
The screenshot is taken from the surface using this element’s content-box.
use headless_chrome::{protocol::page::ScreenshotFormat, Browser};
let browser = Browser::default()?;
let png_data = browser.wait_for_initial_tab()?
.navigate_to("https://en.wikipedia.org/wiki/WebKit")?
.wait_for_element("#mw-content-text > div > table.infobox.vevent")?
.capture_screenshot(ScreenshotFormat::PNG)?;
pub fn set_input_files(&self, file_paths: &[&str]) -> Result<&Self>
sourcepub fn scroll_into_view(&self) -> Result<&Self>
pub fn scroll_into_view(&self) -> Result<&Self>
Scrolls the current element into view
Used prior to any action applied to the current element to ensure action is duable.
Examples found in repository?
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452
pub fn move_mouse_over(&self) -> Result<&Self> {
self.scroll_into_view()?;
let midpoint = self.get_midpoint()?;
self.parent.move_mouse_to_point(midpoint)?;
Ok(self)
}
pub fn click(&self) -> Result<&Self> {
self.scroll_into_view()?;
debug!("Clicking element {:?}", &self);
self.call_js_fn("function() { this.click(); return 1; }", vec![], false)?
.value.unwrap();
/* let midpoint = self.get_midpoint()?;
self.parent.click_point(midpoint)?; */
if let Err(_) = self.parent.wait_until_navigated() {
info!("[CLICK] Page load timeout..");
}
// MUST reload DOM in case page refreshed..
self.parent.load_document();
Ok(self)
}
pub fn type_into(&self, text: &str) -> Result<&Self> {
self.click()?;
debug!("Typing into element ( {:?} ): {}", &self, text);
self.parent.type_str(text)?;
Ok(self)
}
pub fn call_js_fn(
&self,
function_declaration: &str,
args: Vec<serde_json::Value>,
await_promise: bool,
) -> Result<Runtime::RemoteObject> {
let mut args = args.clone();
let result = self
.parent
.call_method(Runtime::CallFunctionOn {
object_id: Some(self.remote_object_id.clone()),
function_declaration: function_declaration.to_string(),
arguments: args
.iter_mut()
.map(|v| {
Some(Runtime::CallArgument {
value: Some(v.take()),
unserializable_value: None,
object_id: None,
})
})
.collect(),
return_by_value: Some(false),
generate_preview: Some(true),
silent: Some(false),
await_promise: Some(await_promise),
user_gesture: None,
execution_context_id: None,
object_group: None,
throw_on_side_effect: None,
})?
.result;
Ok(result)
}
pub fn focus(&self) -> Result<&Self> {
self.scroll_into_view()?;
self.parent.call_method(DOM::Focus {
backend_node_id: Some(self.backend_node_id),
node_id: None,
object_id: None,
})?;
Ok(self)
}
/// Returns the inner text of an HTML Element. Returns an empty string on elements with no text.
///
/// Note: .innerText and .textContent are not the same thing. See:
/// https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/innerText
///
/// Note: if you somehow call this on a node that's not an HTML Element (e.g. `document`), this
/// will fail.
/// ```rust
/// # use anyhow::Result;
/// # fn main() -> Result<()> {
/// #
/// use headless_chrome::Browser;
/// use std::time::Duration;
/// let browser = Browser::default()?;
/// let url = "https://web.archive.org/web/20190403224553/https://en.wikipedia.org/wiki/JavaScript";
/// let inner_text_content = browser.wait_for_initial_tab()?
/// .navigate_to(url)?
/// .wait_for_element_with_custom_timeout("#Misplaced_trust_in_developers", Duration::from_secs(10))?
/// .get_inner_text()?;
/// assert_eq!(inner_text_content, "Misplaced trust in developers");
/// #
/// # Ok(())
/// # }
/// ```
pub fn get_inner_text(&self) -> Result<String> {
let text: String = serde_json::from_value(
self.call_js_fn("function() { return this.innerText }", vec![], false)?
.value
.unwrap(),
)?;
Ok(text)
}
/// Get the full HTML contents of the element.
///
/// Equivalent to the following JS: ```element.outerHTML```.
pub fn get_content(&self) -> Result<String> {
let html = self.
call_js_fn("function() { return this.outerHTML }", vec![], false)?
.value
.unwrap();
Ok(String::from(html.as_str().unwrap()))
}
pub fn get_computed_styles(&self) -> Result<Vec<CSSComputedStyleProperty>> {
let styles = self
.parent
.call_method(CSS::GetComputedStyleForNode {
node_id: self.node_id,
})?
.computed_style;
Ok(styles)
}
pub fn get_description(&self) -> Result<DOM::Node> {
let node = self
.parent
.call_method(DOM::DescribeNode {
node_id: None,
backend_node_id: Some(self.backend_node_id),
depth: None,
object_id: None,
pierce: None,
})?
.node;
Ok(node)
}
/// Capture a screenshot of this element.
///
/// The screenshot is taken from the surface using this element's content-box.
///
/// ```rust,no_run
/// # use anyhow::Result;
/// # fn main() -> Result<()> {
/// #
/// use headless_chrome::{protocol::page::ScreenshotFormat, Browser};
/// let browser = Browser::default()?;
/// let png_data = browser.wait_for_initial_tab()?
/// .navigate_to("https://en.wikipedia.org/wiki/WebKit")?
/// .wait_for_element("#mw-content-text > div > table.infobox.vevent")?
/// .capture_screenshot(ScreenshotFormat::PNG)?;
/// #
/// # Ok(())
/// # }
/// ```
pub fn capture_screenshot(
&self,
format: Page::CaptureScreenshotFormatOption,
) -> Result<Vec<u8>> {
self.scroll_into_view()?;
self.parent.capture_screenshot(
format,
Some(90),
Some(self.get_box_model()?.content_viewport()),
true,
)
}
pub fn get_attributes(&self) -> Result<HashMap<String, String>>
sourcepub fn get_box_model(&self) -> Result<BoxModel>
pub fn get_box_model(&self) -> Result<BoxModel>
Get boxes for this element
Examples found in repository?
441 442 443 444 445 446 447 448 449 450 451 452
pub fn capture_screenshot(
&self,
format: Page::CaptureScreenshotFormatOption,
) -> Result<Vec<u8>> {
self.scroll_into_view()?;
self.parent.capture_screenshot(
format,
Some(90),
Some(self.get_box_model()?.content_viewport()),
true,
)
}