为了进行竞争分析、价格监控和市场研究,从电子商务网站中抓取产品数据非常重要。您可以使用 Python 高效地从产品页面抓取数据。在本指南中,我们将演示如何结合使用请求和 lxml 从在线商店中抓取产品信息。
电子商务搜刮涉及从在线商店中提取产品详细信息,如名称、价格和 ID。Python 及其多功能库使这项任务变得高效而简单。在本指南中,我们将从 Costco 网站抓取产品信息。
在开始搜索之前,请确保您已经安装了必要的 Python 库:
pip install requests
pip install lxml
我们将重点从网站的特定产品页面中提取产品名称、产品功能和产品品牌。
要从任何网站中提取数据,您都需要了解网页的结构。打开一个网站页面,检查您要抓取的元素(例如,产品名称、功能品牌等)。
首先,我们将使用请求库向产品页面发送 HTTP GET 请求。我们还将设置请求标头,以模拟真实的浏览器请求。
import requests
# 要搜索的产品 URL 列表
urls = [
"https://www.costco.com/kirkland-signature-men's-sneaker.product.4000216649.html",
"https://www.costco.com/adidas-ladies'-puremotion-shoe.product.4000177646.html"
]
headers = {
'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
'accept-language': 'en-US,en;q=0.9',
'cache-control': 'no-cache',
'dnt': '1',
'pragma': 'no-cache',
'sec-ch-ua': '"Not/A)Brand";v="99", "Google Chrome";v="91", "Chromium";v="91"',
'sec-ch-ua-mobile': '?0',
'sec-fetch-dest': 'document',
'sec-fetch-mode': 'navigate',
'sec-fetch-site': 'same-origin',
'sec-fetch-user': '?1',
'upgrade-insecure-requests': '1',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
}
# 循环浏览每个 URL 并发送 GET 请求
for url in urls:
response = requests.get(url, headers=headers)
if response.status_code == 200:
html_content = response.text
# 后续步骤将增加进一步处理
else:
print(f"Failed to retrieve {url}. Status code: {response.status_code}")
我们将使用 lxml 从解析的 HTML 中提取所需的数据点。
from lxml import html
# 用于存储刮擦数据的列表
scraped_data = []
# 循环浏览每个 URL 并发送 GET 请求
for url in urls:
response = requests.get(url)
if response.status_code == 200:
html_content = response.content
# 使用 lxml 解析 HTML 内容
tree = html.fromstring(html_content)
# 使用 XPath 提取数据
product_name = tree.xpath('//h1[@automation-id="productName"]/text()')[0].strip()
product_feature = tree.xpath('//ul[@class="pdp-features"]//li//text()')
product_brand = tree.xpath('//div[@itemprop="brand"]/text()')[0].strip()
# 将提取的数据添加到列表中
scraped_data.append({'Product Name': product_name, 'Product Feature': product_feature, 'Brand': product_brand})
else:
print(f"Failed to retrieve {url}. Status code: {response.status_code}")
# 打印扫描数据
for item in scraped_data:
print(item)
网站通常会采取反僵尸措施。使用代理和轮换用户代理有助于避免被发现。
使用带 IP 授权的代理:
proxies = {
'http': 'http://your_proxy_ip:your_proxy_port',
'https': 'https://your_proxy_ip:your_proxy_port'
}
response = requests.get(url, proxies=proxies)
旋转用户代理:
import random
user_agents = [
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
# 根据需要添加更多用户代理
]
headers['user-agent'] = random.choice(user_agents)
response = requests.get(url, headers=headers)
最后,我们将把搜索到的数据保存到 CSV 文件中,以便进一步分析。
import csv
csv_file = 'costco_products.csv'
fieldnames = ['Product Name', 'Product Feature', 'Brand']
# 将数据写入 CSV 文件
try:
with open(csv_file, mode='w', newline='', encoding='utf-8') as file:
writer = csv.DictWriter(file, fieldnames=fieldnames)
writer.writeheader()
for item in scraped_data:
writer.writerow(item)
print(f"Data saved to {csv_file}")
except IOError:
print(f"Error occurred while writing data to {csv_file}")
import requests
import urllib3
from lxml import html
import csv
import random
import ssl
ssl._create_default_https_context = ssl._create_stdlib_context
urllib3.disable_warnings()
# 要搜索的产品 URL 列表
urls = [
"https://www.costco.com/kirkland-signature-men's-sneaker.product.4000216649.html",
"https://www.costco.com/adidas-ladies'-puremotion-shoe.product.4000177646.html"
]
# 页眉
headers = {
'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
'accept-language': 'en-US,en;q=0.9',
'cache-control': 'no-cache',
'dnt': '1',
'pragma': 'no-cache',
'sec-ch-ua': '"Not/A)Brand";v="99", "Google Chrome";v="91", "Chromium";v="91"',
'sec-ch-ua-mobile': '?0',
'sec-fetch-dest': 'document',
'sec-fetch-mode': 'navigate',
'sec-fetch-site': 'same-origin',
'sec-fetch-user': '?1',
'upgrade-insecure-requests': '1',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
}
# 旋转请求的用户代理列表
user_agents = [
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
# 根据需要添加更多用户代理
]
# 轮换请求的代理列表
proxies = [
{'http': 'http://your_proxy_ip:your_proxy_port', 'https': 'https://your_proxy_ip:your_proxy_port'},
{'http': 'http://your_proxy_ip2:your_proxy_port2', 'https': 'https://your_proxy_ip2:your_proxy_port2'},
# 根据需要添加更多代理
]
# 用于存储刮擦数据的列表
scraped_data = []
# 循环浏览每个 URL 并发送 GET 请求
for url in urls:
# 为请求标头随机选择一个用户代理
headers['user-agent'] = random.choice(user_agents)
# 为请求选择一个随机代理
proxy = random.choice(proxies)
# 向 URL 发送 HTTP GET 请求,并附带标头和代理
response = requests.get(url, headers=headers, proxies=proxy, verify=False)
if response.status_code == 200:
# 存储响应中的 HTML 内容
html_content = response.content
# 使用 lxml 解析 HTML 内容
tree = html.fromstring(html_content)
# 使用 XPath 提取数据
product_name = tree.xpath('//h1[@automation-id="productName"]/text()')[0].strip()
product_feature = tree.xpath('//ul[@class="pdp-features"]//li//text()')
product_brand = tree.xpath('//div[@itemprop="brand"]/text()')[0].strip()
# 将提取的数据添加到列表中
scraped_data.append({'Product Name': product_name, 'Product Feature': product_feature, 'Brand': product_brand})
else:
# 如果请求失败,则打印错误信息
print(f"Failed to retrieve {url}. Status code: {response.status_code}")
# CSV 文件设置
csv_file = 'costco_products.csv'
fieldnames = ['Product Name', 'Product Feature', 'Brand']
# 将数据写入 CSV 文件
try:
with open(csv_file, mode='w', newline='', encoding='utf-8') as file:
writer = csv.DictWriter(file, fieldnames=fieldnames)
writer.writeheader()
for item in scraped_data:
writer.writerow(item)
print(f"Data saved to {csv_file}")
except IOError:
# 如果写入文件失败,则打印错误信息
print(f"Error occurred while writing data to {csv_file}")
使用 Python 从 Costco 等电子商务网站抓取信息是收集产品信息以进行分析并做出战略决策的有效方法。正确使用 Requests 和 Lxml 等库可实现自动提取过程,并能处理 HTML 内容,同时还能有效实施反僵尸 API。需要注意的是,必须始终遵守合乎道德的刮擦协议。
Мы получили вашу заявку!
Ответ будет отправлен на почту в ближайшее время.
С уважением proxy-seller.com!
评论: 0