2_run_aplus_image_5.py
解析已经下载的 A+ 页面,先过滤掉亚马逊的灰像素占位图,再把真正的大图地址提取出来入库。是三步链路的第二步,重点在「挑图」——直接取 src 很容易抓到一堆 1×1 的无效图片。
import os
import pymysql
from bs4 import BeautifulSoup
from datetime import datetime
import time
import traceback
excluded_urls = [
'https://images-na.ssl-images-amazon.com/images/G/01/x-locale/common/grey-pixel.gif',
]
directory = r'L:\download'
replacements = [
('.__CR0,0,1464,600_PT0_SX1464_V1___', ''),
('.__CR0,0,970,600_PT0_SX970_V1___', ''),
('.__CR0,0,2928,1200_PT0_SX1464_V1___', ''),
('.__CR0,0,970,300_PT0_SX970_V1___', ''),
]
db_config = {
'host': '',
'user': '',
'password': '',
'database': ''
}
# 日志配置
log_dir = os.path.join(directory, 'processing_logs')
os.makedirs(log_dir, exist_ok=True)
def log_success(asin, filename, urls):
log_file = os.path.join(log_dir, 'success.log')
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
with open(log_file, 'a', encoding='utf-8') as f:
f.write(f"[{timestamp}] {filename} ({asin}) processed successfully. URLs: {urls}\n")
def log_error(filename, error_msg):
log_file = os.path.join(log_dir, 'error.log')
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
with open(log_file, 'a', encoding='utf-8') as f:
f.write(f"[{timestamp}] {filename} | Error: {error_msg}\n")
def log_deletion(filename, success=True):
log_file = os.path.join(log_dir, 'deletion.log')
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
status = "Success" if success else "Failed"
with open(log_file, 'a', encoding='utf-8') as f:
f.write(f"[{timestamp}] {filename} | Deletion {status}\n")
def process_files(cursor):
processed_files = 0
for filename in os.listdir(directory):
file_path = os.path.join(directory, filename)
# 跳过不符合条件的文件
if not (
filename.endswith(('.html', '.htm', '.qaqtools'))
and os.path.getsize(file_path) > 1 * 1024 * 1024
):
continue
asin = os.path.splitext(filename)[0]
processed_files += 1
try:
# 读取并解析文件
with open(file_path, 'r', encoding='utf-8') as file:
text = file.read()
soup = BeautifulSoup(text, 'html.parser')
# 提取图片URL
divs = soup.select(
'div.celwidget.aplus-module.premium-module-2-fullbackground-image.aplus-premium, '
'div.a-section.a-spacing-none.aplus-card-image, '
'div.aplus-module-wrapper.aplus-3p-fixed-width, '
'div.apm-eventhirdcol.apm-floatleft, '
'div.apm-hero-image, '
'div.a-section.a-spacing-none.background-image, '
'div.a-section.a-spacing-none .aplus-module-section.aplus-display-table-cell.aplus-image-section'
)
image_urls = set()
for div in divs:
for img in div.find_all('img'):
src = img.get('src')
if src:
# 应用替换规则
for old, new in replacements:
src = src.replace(old, new)
if src not in excluded_urls:
image_urls.add(src)
if not image_urls:
raise ValueError("No valid image URLs found")
# 插入数据库
combined_urls = '|'.join(image_urls)
cursor.execute(
"INSERT INTO aplus_urls (asin, urls, date) VALUES (%s, %s, %s)",
(asin, combined_urls, datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
)
cursor.connection.commit()
# 记录成功日志
log_success(asin, filename, combined_urls)
except Exception as e:
error_msg = f"{str(e)}\n{traceback.format_exc()}"
log_error(filename, error_msg)
if cursor.connection:
cursor.connection.rollback()
finally:
# 无论成功失败都尝试删除文件
try:
os.remove(file_path)
log_deletion(filename)
except Exception as e:
log_deletion(filename, success=False)
log_error(filename, f"File deletion failed: {str(e)}")
return processed_files > 0
try:
wait_time = 55
while True:
connection = None
try:
connection = pymysql.connect(**db_config)
cursor = connection.cursor()
# 处理文件并检查是否有新文件
has_processed = process_files(cursor)
if has_processed:
print("文件处理完成,重置等待时间")
wait_time = 5
else:
print(f"无新文件,等待 {wait_time} 秒...")
time.sleep(wait_time)
wait_time = min(wait_time * 144, 300) # 最大等待300秒(5分钟)
except pymysql.MySQLError as err:
print(f"数据库连接失败: {err}")
time.sleep(5)
finally:
if cursor:
cursor.close()
if connection:
connection.close()
except KeyboardInterrupt:
print("用户中断操作")
# 关闭日志文件等清理操作可以在此处添加