使用 Python 浏览沃尔玛数据指南

评论: 0

网络抓取是一种强大的方法,可从网站中提取数据用于不同目的,如分析、研究和商业智能。本教程将重点介绍关键策略和技术,帮助您使用 Python 搜刮沃尔玛的产品信息。沃尔玛刮削提供了一个示例,在该示例中,我们可以挖掘沃尔玛网站下不同页面中的产品详细信息,如名称、价格或评论。

本指南将使用 requests 库发出 HTTP 请求,并使用 lxml 库解析 HTML 内容。

设置环境

在开始之前,请确保您的计算机上安装了 Python。您可以使用 pip 安装所需的库:

pip install requests
pip install  lxml
pip install urllib3

接下来,让我们导入必要的库:

  • requests:用于发出 HTTP 请求以检索网页;
  • lxml: 用于解析 HTML 内容;
  • csv: 用于写入文件。
  • csv:用于将提取的数据写入 CSV 文件;
  • 随机:用于选择随机代理和用户代理字符串。
import requests from lxml import html import csv import random import urllib3 import ssl

定义产品 URL

要搜索的沃尔玛产品 URL 列表。

product_urls = [
    'link with https',
    'link with https',
    'link with https'
]

用户代理字符串和代理

要对网站进行抓取,使用正确的标头(尤其是 User-Agent 标头)是非常重要的,这样才能模仿来自实际浏览器的请求。此外,使用可轮换代理服务器还可以避免因网站所有者采取的反僵尸措施而受到限制。下面是 User-Agent 字符串的示例,以及如何集成需要基于 IP 地址授权的代理服务器的说明。

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 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
    'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
]

proxy = [
    '<ip>:<port>',
    '<ip>:<port>',
    '<ip>:<port>',
]

请求标题

设置标头以模仿浏览器请求,避免被发现。

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-IN,en;q=0.9',
    'dnt': '1',
    'priority': 'u=0, i',
    'sec-ch-ua': '"Not/A)Brand";v="8", "Chromium";v="126", "Google Chrome";v="126"',
    'sec-ch-ua-mobile': '?0',
    'sec-ch-ua-platform': '"Linux"',
    'sec-fetch-dest': 'document',
    'sec-fetch-mode': 'navigate',
    'sec-fetch-site': 'none',
    'sec-fetch-user': '?1',
    'upgrade-insecure-requests': '1',
}

初始化数据存储

创建一个空列表来存储产品详细信息。

product_details = []

URL 页面的枚举过程如下:对每个 URL 页面,使用随机选择的用户代理和代理发送 GET 请求。收到 HTML 响应后,对其进行解析,以提取产品名称、价格和评论等详细信息。提取的数据以字典形式存储,随后将其添加到之前创建的列表中。

for url in product_urls:
   headers['user-agent'] = random.choice(user_agents)
   proxies = {
       'http': f'http://{random.choice(proxy)}',
       'https': f'http://{random.choice(proxy)}',
   }
   try:
       # 向 URL 发送 HTTP GET 请求
       response = requests.get(url=url, headers=headers, proxies=proxies, verify=False)
       print(response.status_code)
       response.raise_for_status()
   except requests.exceptions.RequestException as e:
       print(f'Error fetching data: {e}')

   # 使用 lxml 解析 HTML 内容
   parser = html.fromstring(response.text)
   # 提取产品标题
   title = ''.join(parser.xpath('//h1[@id="main-title"]/text()'))
   # 提取产品价格
   price = ''.join(parser.xpath('//span[@itemprop="price"]/text()'))
   # 提取审查详情
   review_details = ''.join(parser.xpath('//div[@data-testid="reviews-and-ratings"]/div/span[@class="w_iUH7"]/text()'))

   # 将提取的详细信息存储在字典中
   product_detail = {
       'title': title,
       'price': price,
       'review_details': review_details
   }
   # 将产品详细信息添加到列表中
   product_details.append(product_detail)

标题:

1.png

价格:

2.png

审查细节:

3.png

将数据保存为 CSV

  1. 打开一个新的 CSV 文件进行编写。
  2. 定义 CSV 文件的字段名(列)。
  3. 创建 csv.DictWriter 对象,将字典写入 CSV 文件。
  4. 将标题行写入 CSV 文件。
  5. 循环浏览 product_details 列表,并将每个产品字典作为一行写入 CSV 文件。
with open('walmart_products.csv', 'w', newline='') as csvfile:
    fieldnames = ['title', 'price', 'review_details']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writeheader()
    for product_detail in product_details:
        writer.writerow(product_detail)

完整代码:

以下是完整的代码,并附有注释,以帮助您更好地理解代码

import requests
from lxml import html
import csv
import random
import urllib3
import ssl

ssl._create_default_https_context = ssl._create_stdlib_context
urllib3.disable_warnings()


# 要搜索的产品 URL 列表
product_urls = [
   'link with https',
   'link with https',
   'link with https'
]

# 用于匿名的随机用户代理字符串
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 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
   'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
]

# IP 轮换代理列表
proxy = [
    '<ip>:<port>',
    '<ip>:<port>',
    '<ip>:<port>',
]


# 模仿浏览器请求的标头
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-IN,en;q=0.9',
   'dnt': '1',
   'priority': 'u=0, i',
   'sec-ch-ua': '"Not/A)Brand";v="8", "Chromium";v="126", "Google Chrome";v="126"',
   'sec-ch-ua-mobile': '?0',
   'sec-ch-ua-platform': '"Linux"',
   'sec-fetch-dest': 'document',
   'sec-fetch-mode': 'navigate',
   'sec-fetch-site': 'none',
   'sec-fetch-user': '?1',
   'upgrade-insecure-requests': '1',
}

# 初始化一个空列表,用于存储产品详细信息
product_details = []

# 循环浏览每个产品的 URL
for url in product_urls:
   headers['user-agent'] = random.choice(user_agents)
   proxies = {
       'http': f'http://{random.choice(proxy)}',
       'https': f'http://{random.choice(proxy)}',
   }
   try:
       # 向 URL 发送 HTTP GET 请求
       response = requests.get(url=url, headers=headers, proxies=proxies, verify=False)
       print(response.status_code)
       response.raise_for_status()
   except requests.exceptions.RequestException as e:
       print(f'Error fetching data: {e}')

   # 使用 lxml 解析 HTML 内容
   parser = html.fromstring(response.text)
   # 提取产品标题
   title = ''.join(parser.xpath('//h1[@id="main-title"]/text()'))
   # 提取产品价格
   price = ''.join(parser.xpath('//span[@itemprop="price"]/text()'))
   # 提取审查详情
   review_details = ''.join(parser.xpath('//div[@data-testid="reviews-and-ratings"]/div/span[@class="w_iUH7"]/text()'))

   # 将提取的详细信息存储在字典中
   product_detail = {
       'title': title,
       'price': price,
       'review_details': review_details
   }
   # 将产品详细信息添加到列表中
   product_details.append(product_detail)

# 将提取的数据写入 CSV 文件
with open('walmart_products.csv', 'w', newline='') as csvfile:
   fieldnames = ['title', 'price', 'review_details']
   writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
   writer.writeheader()
   for product_detail in product_details:
       writer.writerow(product_detail)

我们的教程演示了如何利用 Python 库从沃尔玛抓取产品数据,并将其保存为 CSV 格式以便进行后续分析。所提供的脚本是最基本的,它提供了一个可以增强的基础,以提高抓取过程的效率。增强功能可包括在请求之间引入随机延迟以模仿人类浏览模式、实施用户代理和代理轮换以避免被检测到,以及开发一个强大的错误处理系统以管理潜在的搜刮中断或失败。

评论:

0 评论