[英]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.