python - 无法从 python 中的 div 标签读取文本

标签 python html selenium xpath web-scraping

对于 driver.find_elements_by_xpath("//div[@class='d3-tip n']") 中的位置: 样式 =position.get_attribute('样式') 不透明度 = 样式[:32] 如果不透明度==“position:absolute;不透明度:1;”: tooltipmessage = driver.find_element_by_xpath('//div[contains(@style,"%s")]' % 不透明度) 时间. sleep (3) print tooltipmessage.text我有 2 个具有相同类的 div 标签(“d3-tip n”)。当我将鼠标悬停时,样式属性中的不透明度更改为“1”,并且我想打印该 div 标签中的文本。

我编写了以下代码,但由于某种原因它没有打印任何内容。

注意 - 我也尝试过position.text,但这也不起作用。

附件是 HTML 代码,显示具有相同类的 2 个 div 项目,带有 SQL 查询的项目是我要打印的文本。 enter image description here

for position in driver.find_elements_by_xpath('//div[@class="d3-tip n"]'):
                    style = position.get_attribute('style')
                    opacity = style[:32]
                    if opacity == "position: absolute; opacity: 1;":
                       print position

最佳答案

您可以仅获取按类名找到的 2 个 div 中的第一个 div:

element = driver.find_elements_by_xpath('//div[@class="d3-tip n"]')[0]
print element.text

另一个选项是检查 div 标记中是否没有子级:

element = driver.find_element_by_xpath('//div[@class="d3-tip n"][count(*)=0]')
print element.text

另一个选项是检查 div 文本内是否有 select 文本:

element = driver.find_element_by_xpath('//div[@class="d3-tip n"][contains(text(), "select")]')
print element.text

关于python - 无法从 python 中的 div 标签读取文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23501764/

相关文章:

testing - Selenium 错误 : The Selenium Server is not active on host localhost at port 4444

java - 无法使用selenium webdriver点击 "Browse"按钮

python - 休息 api 触发大厅管道/工作

python - 如何在 tkinter 中将文本标签居中?

php - 提交 HTML 表单后如何在页面刷新时停止重新提交表单

html - :nth-child() and :nth-of-type() not working

javascript 使用 blob 从本地硬盘加载图像

c# - 自动测试从设置中列出的代码中抛出错误,尽管它已经在其他测试中正确执行

Python 打包 : wheels vs tarball (tar. gz)

python - 比较 2 个字典中的键和值