Use xpath to extract the text of the attribute value

The method of using xpath to extract the text of the attribute value is as follows:

  1. Use the @ symbol in an xpath expression to select attributes of an element. For example, if you want to select the class attribute of an element, you can use @class.

  2. Use the text function to get the text value of an element. For example, to get the text of the class attribute value, the following xpath expression can be used:

text(@class)
  1. Method to apply an xpath expression to select elements to get the text of the attribute value.

For example, when using the lxml library, you can use the following code:

element = root.xpath('//div[@class="example"]')[0]
class_value = element.xpath('text(@class)')

Here, root is the root element of the document, //div[@class="example"] is an xpath expression to select the div element whose class attribute value is "example", and text(@class) is to extract the class attribute value The xpath expression of the text.

Guess you like

Origin blog.csdn.net/weixin_35753291/article/details/129076882