Fool's blog Fool's blog
首页
  • Ansible
  • Jenkins
  • Docker
  • Kubernetes
  • Linux常用命令
  • Git
  • Nginx
  • PVE
  • Samaba
  • Python
  • Go
GitHub (opens new window)

The Fool

运维萌新
首页
  • Ansible
  • Jenkins
  • Docker
  • Kubernetes
  • Linux常用命令
  • Git
  • Nginx
  • PVE
  • Samaba
  • Python
  • Go
GitHub (opens new window)
  • Python

    • bs4
    • faker
  • Go

  • 编程语言
  • Python
The Fool
2025-11-02

bs4

python3环境

先安装所需的库

pip install requests beautifulsoup4 pymysql
1
import requests
from bs4 import BeautifulSoup
from datetime import datetime
import pymysql

# 定义要爬取的目标 URL
url = 'https://clients.zgovps.com/index.php?/cart/special-offer/'
# 设置请求头,模仿浏览器访问
headers = {
     'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36',
 }
db_config = {
    'host': 'ip',           # 数据库主机
    'user': 'user',       # 替换为你的数据库用户名
    'password': 'password',   # 替换为你的数据库密码
    'database': 'database',        # 使用的数据库
    'charset': 'utf8mb4',          # 设置字符集
}
# 发送 GET 请求获取网页内容
response = requests.get(url, headers=headers)
# 使用 BeautifulSoup 解析 HTML 文档,指定解析器为 'html.parser'
html_doc = response.text
soup = BeautifulSoup(html_doc, 'html.parser')
# 查找所有符合条件的商品名称(根据 HTML 标签 'strong' 和类名 'mb-3')
shop_names = soup.find_all('strong',class_='mb-3')
# 查找所有商品价格,使用 'option' 标签来提取价格信息
shop_prices = soup.find_all('option')
# 查找所有库存信息,使用 'button' 标签来提取库存状态
shop_stocks = soup.find_all('button')
#  查找所有符合条件的商品详情(根据 HTML 标签 'div' 和类名 'my-3')
shop_details = soup.find_all('div', class_='my-3')
# 获取当前时间
current_date = datetime.now().strftime('%Y-%m-%d %H:%M:%S')




def w_txt(shop_names, shop_prices, shop_stocks, shop_details, current_date):
    date = datetime.now().strftime('%Y-%m-%d')
    file_path = f'{date}.txt'
    # 打开一个文件,以写入模式写入解析出的数据,并确保使用 UTF-8 编码,'a'表示追加
    with open(file_path, 'a', encoding='utf-8') as f:
        # 写入当前日期和时间
        f.write(f"Date: \n{current_date}\n")
        f.write("=" * 40 + "\n")
        for i in range(len(shop_names)):
            f.write(f"Product: {shop_names[i].text}\n")
            li_items = shop_details[i].find_all('li')
            formatted_detail = '\n'.join([li.text.strip() for li in li_items])  # 合并所有 <li> 标签的文本,使用换行符分隔
            f.write(f"Detail:\n{formatted_detail}\n")
            f.write(f"Price: {shop_prices[i].text}\n")
            f.write(f"Stock Status: {shop_stocks[i].text}\n")
            f.write("-" * 40+"\n")
    # 打印提示信息,表示操作完成
    print(f"数据已成功写入{date}文件.")

def w_mysql(db_config,shop_names, shop_prices, shop_stocks, shop_details, current_date):
    # 创建数据库连接
    try:
        connection = pymysql.connect(**db_config)
        cursor = connection.cursor()

        # 插入数据到数据库
        for i in range(len(shop_names)):
            product_name = shop_names[i].text.strip()

            # 提取每个商品的详细信息并格式化
            detail_div = shop_details[i]
            li_items = detail_div.find_all('li')
            detail = '\n'.join([li.text.strip() for li in li_items])

            price = shop_prices[i].text.strip()
            stock_status = shop_stocks[i].text.strip()

            # 插入记录
            insert_query = """
            INSERT INTO zgo (product_name, details, price, stock_status, date_added)
            VALUES (%s, %s, %s, %s, %s)
            """
            cursor.execute(insert_query, (product_name, detail, price, stock_status, current_date))

        # 提交事务
        connection.commit()
        print("数据已成功插入到数据库.")

    except pymysql.MySQLError as err:
        print(f"数据库错误: {err}")
    finally:
        # 关闭连接
        if connection:
            cursor.close()
            connection.close()


w_txt(shop_names, shop_prices, shop_stocks, shop_details, current_date)

w_mysql(db_config,shop_names, shop_prices, shop_stocks, shop_details, current_date)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#bs4
faker

faker→

最近更新
01
viper
12-20
02
Jenkins基础
12-19
03
Jenkins实践
12-19
更多文章>
Theme by Vdoing | Copyright © 2024-2025 The Fool
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式