关于python 用selenium获取div里面的文本跟文本对应的id值?

请问怎么用selenium 获取下面的文本信息(pip,pi,ii)由于它们的id是动态的,有时div里面会有相同的文本内容,可不可以再根据文本获取对…
关注者
4
被浏览
8,282

1 个回答

【解决方案(实测有效)】

find_str="pip"
xpath_str = "//div[text()='"+find_str+"']"
# 元素定位
elem = driver.find_element_by_xpath(xpath_str)
print('定位完成:'+str(elem))
# id获取
id = driver.find_element_by_xpath(xpath_str).get_attribute("id")
print('id获取完成:'+id)

【全部代码】

  • 1.html
<div>
<div id="id_pip">pip</div>
<div id="id_pi">pi</div>
<div id="id_li">ii</div>
</div>
  • python代码
from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
import time
driver = webdriver.Chrome()
# 变量设定
url="localhost:1001/1.html"
driver.get(url)
find_str="pip"
xpath_str = "//div[text()='"+find_str+"']"
# 元素定位
elem = driver.find_element_by_xpath(xpath_str)
print('定位完成:'+str(elem))
# id获取
id = driver.find_element_by_xpath(xpath_str).get_attribute("id")
print('id获取完成:'+id)
  • 运行结果
定位完成:<selenium.webdriver.remote.webelement.WebElement (session="13e3a8619bb6596101cafd90fb47cd78", element="0.6531326715688968-1")>
id获取完成:id_pip

【参考文献】

原文:

7. By.xpath()
……省略一大段……
c. 用Text关键字,定位代码如下:
1 driver.findElement(By.xpath(“//*[text()=’退出’]));
这个方法可谓相当霸气啊。直接查找页面当中所有的退出二字,根本就不用知道它是个a元素了。这种方法也经常用于纯文字的查找。

原文

get_attribute(name)
Gets the given attribute or property of the element.
This method will first try to return the value of a property with the given name. If a property with that name doesn’t exist, it returns the value of the attribute with the same name. If there’s no attribute with that name, None is returned.
Values which are considered truthy, that is equals “true” or “false”, are returned as booleans. All other non-None values are returned as strings. For attributes or properties which do not exist, None is returned.