【问题标题】:How to get select value of a HREF element through Cheerio如何通过 Cheerio 获取 HREF 元素的选择值
【发布时间】:2021-02-26 07:43:37
【问题描述】:

我有一个 HTML 源代码。

<div class="placeholderClass">
    <h2>THIS IS A PLACEHOLDER</h2> <br>
    <p>I want to redirect you to my website over here <a href="https://www.placeholder.com/path/app/stores/HubArticleView?hubId=Hub-100000&amp;placeHoldingID=100000&amp;userID=10000&amp;nameID=40&amp;viewID=10000#parentHorizontalTab2">PLACEHOLDER VIEW</a>.
    </p>
</div>

我想从此源获取 href 元素


const $ = cheerio.load(body); // body is the HTML that is loaded above
const IDInfo = {};

const HREF = $('.placeholderClass > h2 > br > p[href])

我正在做最后一行以尝试获取 HREF 链接,因此我无法提取它。

【问题讨论】:

  • 您有语法错误,缺少字符串中的右引号。

标签: javascript html jquery jquery-selectors cheerio


【解决方案1】:

这是关于 css 选择器和 jQuery/Cheerio 的基本内容。属性选择器不返回属性而是节点。你想要的是这样的:

$('.placeholderClass > h2 > br > p[href]').attr('href');

【讨论】:

    【解决方案2】:

    document.getElementByTagName("a").getAttribute("href");

    【讨论】:

    • 这可能在 Node 中不起作用,因为 OP 不使用 jsDom 而是 Cheeerio。 document 对象是(如果不使用 jsDOM)存在于浏览器中的东西。
    猜你喜欢
    • 2023-02-02
    • 2018-03-12
    • 1970-01-01
    • 2011-03-07
    • 2020-05-13
    • 1970-01-01
    • 1970-01-01
    • 2012-12-23
    • 2015-12-15
    相关资源
    最近更新 更多