You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中使用Selenium如何获取两个相同class属性元素的不同值?

获取第二个class为twitter-label元素文本值的方法

原生JavaScript实现

  • 方法1:使用querySelectorAll接口
// querySelectorAll返回匹配选择器的所有元素的NodeList集合,索引从0开始,第二个元素取索引1
const secondTwitterLabel = document.querySelectorAll('.twitter-label')[1];
// 获取文本内容并trim去除首尾换行、空格等空白字符
const targetText = secondTwitterLabel.textContent.trim();
console.log(targetText); // 输出结果:Follow
  • 方法2:使用getElementsByClassName接口
// getElementsByClassName返回匹配类名的所有元素的HTMLCollection集合,同样取索引1
const labelCollection = document.getElementsByClassName('twitter-label');
const targetText = labelCollection[1].textContent.trim();

jQuery实现(如果项目引入了jQuery)

// eq(1)获取匹配集合中索引为1的元素,trim去除首尾空白
const targetText = $('.twitter-label').eq(1).text().trim();

注意:由于你提供的HTML结构中span元素内容前后包含换行和空格,所以需要调用trim()方法处理后才能拿到纯净的Follow文本。

内容的提问来源于stack exchange,提问作者Jhon tech

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 04:54:10