在编写脚本之前,让我们先验证一下 Puppeteer 的安装是否成功:
import puppeteer from 'puppeteer';
async function scrapeWalmartData(walmart_url: string): Promise<void> {
// Launch Puppeteer
const browser = await puppeteer.launch({
headless: false,
args: ['--start-maximized'],
defaultViewport: null
})
// Create a new page
const page = await browser.newPage()
// Navigate to the target URL
await page.goto(walmart_url)
// Close the browser
await browser.close()
}
scrapeWalmartData("https://www.walmart.com/ip/Keter-Adirondack-Chair-Resin-Outdoor-Furniture-Teal/673656371")
这里我们打开一个浏览器窗口,新建一个页面,导航至目标 URL,然后关闭浏览器。为了简化操作和便于可视化调试,我以非无头模式全屏打开了浏览器窗口。
现在,让我们看看网站的结构:
要获取产品名称,我们锁定“h1”元素的“itemprop”属性。我们需要提取的是其文本内容。
// Extract product name
const product_name = await page.evaluate(() => {
const name = document.querySelector('h1[itemprop="name"]')
return name ? name.textContent : ''
})
console.log(product_name)
对于评分数值,我们确定了类名以“rating-number”结尾的“span”元素是可靠的。
// Extract product rating number
const product_rating = await page.evaluate(() => {
const rating = document.querySelector('span[class$="rating-number"]')
return rating ? rating.textContent : ''
})
console.log(product_rating)
最后(针对高亮部分),对于评论数量和产品价格,我们同样依赖“itemprop”属性,与上述方法一致。
// Extract product reviews count
const product_reviews = await page.evaluate(() => {
const reviews = document.querySelector('a[itemprop="ratingCount"]')
return reviews ? reviews.textContent : ''
})
console.log(product_reviews)
// Extract product price
const product_price = await page.evaluate(() => {
const price = document.querySelector('span[itemprop="price"]')
return price ? price.textContent : ''
})
console.log(product_price)
接下来处理产品图片,我们需要在 HTML 文档中进一步定位:
这稍显棘手,但并非无法实现。仅凭图片本身无法唯一识别,因此这次我们将锁定其父级元素。于是,我们提取那些“data-testid”属性值设为“media-thumbnail”的“div”元素。
随后,我们将结果转换为 JavaScript 数组,以便将每个元素与其“src”属性建立映射。
// Extract product images
const product_images = await page.evaluate(() => {
const images = document.querySelectorAll('div[data-testid="media-thumbnail"] > img')
const images_array = Array.from(images)
return images ? images_array.map(a => a.getAttribute("src")) : []
})
console.log(product_images)
最后但同样重要的是,我们向下滚动页面以查看产品详情:
我们应用与提取图片相同的逻辑,这次只需利用类名“dangerous-html”。
// Extract product details
const product_details = await page.evaluate(() => {
const details = document.querySelectorAll('div.dangerous-html')
const details_array = Array.from(details)
return details ? details_array.map(d => d.textContent) : []
})
console.log(product_details)
最终结果应如下所示:
Keter Adirondack Chair, Resin Outdoor Furniture, Teal
(4.1)
269 reviews
Now $59.99
[
'https://i5.walmartimages.com/asr/51fc64d9-6f1f-46b7-9b41-8880763f6845.483f270a12a6f1cbc9db5a37ae7c86f0.jpeg?odnHeight=80&odnWidth=80&odnBg=FFFFFF', 'https://i5.walmartimages.com/asr/80977b5b-15c5-435e-a7d6-65f14b2ee9c9.d1deed7ca4216d8251b55aa45eb47a8f.jpeg?odnHeight=80&odnWidth=80&odnBg=FFFFFF',
'https://i5.walmartimages.com/asr/80c1f563-91a9-4bff-bda5-387de56bd8f5.5844e885d77ece99713d9b72b0f0d539.jpeg?odnHeight=80&odnWidth=80&odnBg=FFFFFF', 'https://i5.walmartimages.com/asr/fd73d8f2-7073-4650-86a3-4e809d09286e.b9b1277761dec07caf0e7354abb301fc.jpeg?odnHeight=80&odnWidth=80&odnBg=FFFFFF',
'https://i5.walmartimages.com/asr/103f1a31-fbc5-4ad6-9b9a-a298ff67f90f.dd3d0b75b3c42edc01d44bc9910d22d5.jpeg?odnHeight=80&odnWidth=80&odnBg=FFFFFF', 'https://i5.walmartimages.com/asr/120121cd-a80a-4586-9ffb-dfe386545332.a90f37e11f600f88128938be3c68dca5.jpeg?odnHeight=80&odnWidth=80&odnBg=FFFFFF',
'https://i5.walmartimages.com/asr/47b8397f-f011-4782-bbb7-44bfac6f3fcf.bb12c15a0146107aa2dcd4cefba48c38.jpeg?odnHeight=80&odnWidth=80&odnBg=FFFFFF'
]
[
'The Keter Adirondack chair lets you experience the easy-living comfort of the popular chair but with none of the worries of wood. Combining traditional styling and the look and feel of wood with durable and maintenance-free materials, this chair will find',
'Keter Adirondack Chair, Resin Outdoor Furniture, Gray: Made from an all-weather resistant resin for ultimate durability Weather-resistant polypropylene construction prevents fading, rusting, peeling, and denting - unlike real wood Quick and easy assembly Rotating cup holder Classic comfort redefined Ergonomic design Durable and weather-resistant Worry-free relaxation Dimensions: 31.9" L x 31.5" W x 38" H Seat height is 15.4 in. for a deep bucket seat and tall backrest Chair Weighs 22 lbs. - heavy enough to not blow over in the wind, yet light enough to easily rearrange your patio space 350 lbs. capacity '
]