Selenium 如何获取写在DOM元素上的文本?
Retrieving text from DOM elements in Selenium is typically straightforward and simple. Typically, we use Selenium's attribute to retrieve the text from an element. Here are specific steps and code examples to illustrate how to achieve this:Step 1: Import necessary librariesFirst, ensure Selenium is installed and import the required libraries.Step 2: Launch the WebDriverNext, initialize a WebDriver instance. For example, using Chrome:Step 3: Locate the element you want to retrieve text fromUse Selenium's various locator methods, such as , , or . For instance, if you know the CSS selector:Step 4: Retrieve the text of the elementOnce you have a reference to the element, use the attribute to obtain its text content.ExampleSuppose a webpage has the following HTML structure:The corresponding Selenium script is:This code outputs:This is the fundamental approach for extracting text from DOM elements in Selenium. Adjust the WebDriver path and target URL according to your specific environment.