【问题标题】:JS select all anchor elements inside a tableJS选择表格内的所有锚元素
【发布时间】:2021-07-31 20:21:31
【问题描述】:

我有一个带有表格部分的 html 页面。它由链接组成,我需要全部获取它们,最好是某种数组。当我尝试定位表中的单个链接时,它可以工作,我只需复制 JS 路径就可以了。但无论我做什么,我都无法定位表中的所有链接,它经常返回 null 或给出错误。这是表格中单个行的路径,这有效,但我需要表格内的所有 a href,请帮助!

#anchor-text-chart-section > div.table-container.mob-single-panel > table > tbody > tr:nth-child(3) > td.anchorText > a

【问题讨论】:

  • 如果没有看到您的 HTML,我们无法重现此内容。
  • document.querySelectorAll('#anchor-text-chart-section table a');
  • 返回[object object]。不能是该元素不存在/生成吗?
  • 我正在使用我的雇主帐户到majestic.com,我可以截图或复制粘贴html,够了吗?

标签: javascript css-selectors target


【解决方案1】:
const elements = document.querySelectorAll('#anchor-text-chart-section table a');
const urls = [];
for (const element of elements) {
  urls.push(element.href);
}
console.log(urls);

【讨论】:

  • 你应该在Dev Tool中使用console.log而不是return
  • 你是对的,它奏效了!你能解释一下吗?)我正在尝试用 puppeteer 来做这个,基本上一切都一样,但它不起作用“(节点:10168)UnhandledPromiseRejectionWarning:TypeError:元素不可迭代”
  • code const elements = await page.evaluate(() => document.querySelectorAll('#anchor-text-chart-section table a'));常量网址 = []; for (const element of elements) { urls.push(element.href); } 返回网址; console.log(urls);
  • return 将在function 中使用,我跳过了它,因为我假设你会将它包含在一个函数中
  • 不知道puppeteer,你是不是在加载DOM(内容)后运行函数?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-06-28
  • 1970-01-01
  • 2012-09-09
  • 1970-01-01
  • 1970-01-01
  • 2021-02-03
  • 1970-01-01
相关资源
最近更新 更多