【问题标题】:Getting the href attribute from html gives unwanted results从 html 获取 href 属性会产生不需要的结果
【发布时间】:2020-04-20 09:16:16
【问题描述】:

我基本上是从网站上抓取一些内容,HTML 看起来像这样:

<div>
    <a class="title" href="/recipe/pasta">Pasta Recipe</a>
</div>

现在从网站上刮下来后,我使用 js 来获取 href 属性,如下所示:

html.getElementsByTagName('a')[0].href

现在的问题是它返回:file:///A:/recipe/pasta,但我想要的结果是/recipe/pasta。这是相同问题的 Stack Snippet 示例 - href 导致域被前置,这是不可取的:

console.log(document.getElementsByTagName('a')[0].href);
<div>
    <a class="title" href="/recipe/pasta">Pasta Recipe</a>
</div>

我可以通过基本的字符串操作来解决这个问题,但这似乎很初级。

file:///A: 也是我计算机上的驱动器 A: 驱动器。如果我在另一台计算机上运行它,它将变为file:///C:,代表C: 驱动器。

知道我正在使用 nodeJS 在电子应用程序上执行此操作也可能会有所帮助。

【问题讨论】:

    标签: javascript html node.js web-scraping electron


    【解决方案1】:

    改用getAttribute,只获取属性的普通值,而不是其他:

    const href = document.querySelector('a').getAttribute('href');
    console.log(href);
    <div>
        <a class="title" href="/recipe/pasta">Pasta Recipe</a>
    </div>

    【讨论】:

      猜你喜欢
      • 2013-01-06
      • 1970-01-01
      • 2019-03-13
      • 1970-01-01
      • 2023-01-18
      • 2018-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多