簡體   English   中英

即使標簽存在於 Node JS 中,也找不到帶有 JSsoup 的標簽

[英]Cannot find a tag with JSsoup even though the tag exists in Node JS

我一直在嘗試網絡抓取,並想嘗試使用 Node JS 來實現。 我有一些使用請求模塊和 BeautifulSoup4 在 python 中抓取網頁的經驗,我想在 Node JS 中重新創建我的代碼。 但是,當基本上鏡像我的代碼時(除了更改某些內容以解釋語法差異)時,我找不到我正在尋找的 html 標簽。 我將 JSsoup 與 Node JS 一起使用,因為它是我能找到的最接近 BeautifulSoup 的東西。 到目前為止,這是我的代碼:

const request = require('request');
var jssoup = require('jssoup').default;

const options = {
  url: 'https://kith.com/collections/footwear/products/nkaj7292-002.xml',
  headers: {
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)'
  }
};
function getVariant(error, response, body) {
  if (!error && response.statusCode == 200) {
      var soup = new jssoup(body);
      var nametag = soup.find('title');
      var product = nametag.text;
      console.log(product);
      var sizetag = soup.find('title', { string:'9' });
      console.log(sizetag);
  }
}
request(options, getVariant);

代碼最終正確地找到了一個標簽( <title> Nike Zoom Vomero 5/ACW (Black/Reflect Silver/Anthracite) AT3152-001 </title> )但為第二個標簽返回“未定義”。 作為參考,這是它試圖找到的標簽: <title>9</title>

我也嘗試過使用 = 而不是字典並使用內容和名稱而不是字符串,但到目前為止沒有運氣。 我在這里做錯了什么?

我也嘗試查看 JSsoup 文檔,但它沒有太多關於 find() 的內容。

正如在 source 中看到的那樣,期望任何要匹配的string都作為.find的第三個參數提供,因此:

let sizetag = soup.find('title', undefined, '9');

我同意 Scott Sauyet 的觀點,提出問題可能是明智的,尤其是在修復文檔方面

要使用soup.find獲取<targetElement> 的innerText,請使用:

<targetElement>.contents[0]._text

我還試圖在Node JS 的JSsoup抓取html 並發現它返回一個對象

SoupTag {
  name: 'time',                           // name refers tagname
  contents: [ SoupString {.               // contents is array
      parent: [Circular *2],
      previousElement: [Circular *2],
      nextElement: [SoupTag],
      _text: '22 hours ago'              // here's innerText       
    }],
  attrs: { class: 'post-last-modified-td' },
  hidden: false,
  builder: TreeBuilder {
    EMPTY_ELEMENT_TAGS: Set(24) {...} 
  }
}

這是我的代碼:

find_time = soup.find("time", "post-last-modified-td");
if (find_update != undefined) console.log("Updated", find_time.contents[0]._text); 

它返回:

Updated 22 hours ago

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM