Python Selenium XPath Method for Finding Elements Based on Text Content
- 2021-08-17 00:27:54
- OfStack
Problem phenomenon
There is no id, name in the attribute of the element; Although there is class, it is popular and its position is not fixed. For example, the next 1 page in the page number; How do I find that element?
<a class="paging"> Upper 1 Page </div>
<a class="paging">1</div>
<a class="paging">2</div>
<a class="paging"> Under 1 Page </div>
Solution
text()
text () function text positioning
page_next = driver.find_element(By.XPATH, '//a[text()=" Under 1 Page ")]')
contain()
contains Matches String Fuzzy Positioning Contained in 1 Attribute Value
Locate elements by fuzzy search of element text content;
page_next = driver.find_element(By.XPATH, '//a[contains(text(), " Under 1 Page ")]')
page_next = driver.find_element(By.XPATH, '//a[contains(string(), " Under 1 Page ")]')
Python looks up elements through xpath reads element information through selenium
#coding:utf-8
from selenium import webdriver
import time
url ='http://www.baidu.com'
driver = webdriver.Chrome()
driver.get(url)
time.sleep(1)
e=driver.find_element_by_xpath('//*[@id="lg"]/img')
print e
print e.text
print e.id
print e.tag_name
print type(e)
time.sleep(1)
driver.quit()
e. text Read Element Content
e. tag_name Read element tag name