javascript 如果类 x 包含 z 获取类 y 的链接

标签 javascript web-scraping applescript

我不是 js 专家,但需要在我的 applescript 中执行一些 js。不知道这是否可行,因为 html 页面包含此 div 类的多个实例。

  1. 如果嵌套的 div 类“.product_card__title”包含“我的搜索词”
  2. 从嵌套类“.js-search-product-link”中提取 href 链接
  3. 来自主 div 类“.product_card”

这里接受的版本的替代版本 IN THIS THREAD .

我的 HTML:

<div class="product_card powersearch__product_card">
     <a href="/shop/XYZ" class="js-search-product-link">
  <div class="product_card__image" style="background-image:url(https://image.jpg);"></div>
  <div class="product_card__title">SEARCH FOR THIS TITLE</div>
  <div class="product_card__meta">€14</div></a></div>

我目前拥有的是:

tell application "Safari"
open location "https://teespring.com/search?q=rocker"
delay 5

set theLinks to (do JavaScript "Array.prototype.slice.call(document.querySelectorAll('.product_card')).map(function(d,i){var title = d.querySelector('.product_card__title'),link =  d.querySelector('a');if(title && link && /Rocker/gi.test(title.textContent)){return link.href}})")

end tell

return theLinks

最佳答案

将 yourSearchTerm 替换为您要在下面搜索的任何内容:

 Array.prototype.slice.call(document.querySelectorAll(".product_card"))
    .map(function(d,i){
        var title = d.querySelector(".product_card__title"),
            link =  d.querySelector("a");
        if(title && link && /yourSerchTerm/gi.test(title.textContent)){
            return link.href
        }
    })

对于类为 "product_card" 的所有 div,它将返回一个包含 href 的数组,用于它可以找到的那些,否则 undefined

fiddle : https://jsfiddle.net/ibowankenobi/gc6r2h3v/1/

当 apple 返回最后一个全局值时,它可能有助于更改设置 theLinks 变量的部分:

set theLinks to (do JavaScript "someGlobal = Array.prototype.slice.call(document.querySelectorAll('.product_card')).map(function(d,i){var title = d.querySelector('.product_card__title'),link =  d.querySelector('a');if(title && link && /Rocker/gi.test(title.textContent)){return link.href}})")

关于javascript 如果类 x 包含 z 获取类 y 的链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50348809/

相关文章:

python - 使用 python 抓取隐藏的 jquery 值

macos - 在 Mac 上获取文件的完整网络路径 - 终端

javascript - js2xml 中的 xpath 是否允许我在选择时执行类似 contains 的操作?

python - 如何删除表格行中显示的标题?

javascript - 为什么 Javascript 不从 Adob​​e Bridge 返回值?

Java ScriptEngineManager 不再适用于 Mountain Lion 的 AppleScript

javascript - 将鼠标悬停在父列表上时显示嵌套列表

javascript - 根据可观察到的变化刷新 ViewModel

javascript - jQuery Deferrable、Deferred 和 jQuery Deferred 之间的混淆

javascript - document.documentElement用在哪里?