【问题标题】:Scraping the actual attribute name from webpage?从网页中抓取实际的属性名称?
【发布时间】:2021-04-10 15:52:29
【问题描述】:

如果这是基本问题,我深表歉意,但我似乎无法说出我的问题以在其他地方找到结果。

基本上,我想知道如何使用 Javascript 从网页中抓取 CSS 属性的实际名称。直观地说,我想使用document.querySelectorAll('a [title]'),但这只是一个选择器,用于获取用这些选择器标记的文本内容,不会刮掉实际标题属性的名称本身。

在下面的示例中,document.querySelectorAll('a [title]') 将选择“A Light in the...”正文,而不是“A Light in the Attic”元标题名称。

<h3>
  <a href="catalogue/a-light-in-the-attic_1000/index.html" title="A Light in the Attic">A Light in the...</a>
</h3>

您可以看到为什么这很重要,因为我正在处理的网页在正文中会截断名称,但将其完全写在标题元标记中。

谢谢!

【问题讨论】:

  • 你只是想获取title属性的内容吗?
  • 是的,谢谢!

标签: css web-scraping css-selectors


【解决方案1】:

我提出了两个解决方案。一次性获取所有a标签的title属性内容,点击即可。

要获取title属性的内容,需要使用getAttribute()。但是由于使用了标签集合a,所以我决定使用for循环。

let a = document.querySelectorAll('a');

for (var i = 0; i < a.length; i++) {
  console.log(a[i].getAttribute('title'));
}
<h3>
  <a href="" title="A Light in the Attic1">A Light in the...</a>
  <a href="" title="A Light in the Attic2">A Light in the...</a>
  <a href="" title="A Light in the Attic3">A Light in the...</a>
</h3>

第二种方案,点击时从哪里获取title属性的内容:

let a = document.querySelectorAll('a');

for (var i = 0; i < a.length; i++) {
  a[i].onclick = function(event) {
    event.preventDefault();
    console.log(this.getAttribute('title'));
  }
}
<h3>
  <a href="" title="A Light in the Attic1">A Light in the...</a>
  <a href="" title="A Light in the Attic2">A Light in the...</a>
  <a href="" title="A Light in the Attic3">A Light in the...</a>
</h3>

【讨论】:

  • 非常感谢@s.kuznetsov!我不知道 getAttribute()
  • @Conner,没问题。很高兴为您提供帮助!
猜你喜欢
  • 2022-01-21
  • 2020-10-05
  • 2013-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多