我一直在尝试网页抓取,并想尝试使用 Node JS 来实现这一点。我有一些使用 requests 模块和 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() 的内容。
最佳答案
尽力而为see in the source ,它期望任何要匹配的 string
作为 .find
的第三个参数提供,因此:
let sizetag = soup.find('title', undefined, '9');
我同意 Scott Sauyet 的观点,即提出一个问题可能是明智的,特别是对于修复文档而言
关于javascript - 即使 Node JS 中存在标签,也无法使用 JSsoup 找到标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53770358/