1_run_flush_aplus_urls.py
从数据库里取出待处理的 A+ 页面 URL,用 Selenium 逐个访问并把处理状态回写。这是 A+ 图库采集三步链路里的第一步,负责把 URL 清单跑成真实页面,后两步再去做解析和清理。
import pymysql
import time
import os
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
# 数据库连接配置
config = {
'host': '',
'user': '',
'password': '',
'database': ''
}
def get_db_connection():
"""获取数据库连接"""
return pymysql.connect(**config)
def clean_duplicates():
try:
conn = get_db_connection()
cursor = conn.cursor()
# 创建临时表,排除urls为NULL的项
cursor.execute("""
CREATE TEMPORARY TABLE tmp_table AS
SELECT MAX(id) as id
FROM aplus_asinlist
WHERE urls IS NOT NULL
GROUP BY urls;
""")
# 删除重复项,包含urls为NULL的项
cursor.execute("""
DELETE FROM aplus_asinlist
WHERE id NOT IN (SELECT id FROM tmp_table)
AND urls IS NOT NULL;
""")
# 清理临时表
cursor.execute("DROP TEMPORARY TABLE IF EXISTS tmp_table;")
conn.commit()
print("清除重复项成功!并已删除urls为NULL的项。")
except pymysql.MySQLError as err:
print(f"发生错误: {err}")
finally:
if cursor:
cursor.close()
if conn:
conn.close()
def save_webpages():
# 初始化webdriver
service = Service(executable_path=r'C:/Users/admin/Downloads/chromedriver-win64/chromedriver-win64/chromedriver.exe')
driver = webdriver.Chrome(service=service)
driver.get("https://www.amazon.com")
# 等待用户登录
input("请登录后按回车继续...")
# 指定保存文件夹
save_folder = "L:/download"
if not os.path.exists(save_folder):
os.makedirs(save_folder)
processed_urls = set()
while True:
try:
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute("SELECT urls FROM aplus_asinlist WHERE urls IS NOT NULL;")
urls = cursor.fetchall()
for url_tuple in urls:
url = url_tuple[0]
if url in processed_urls:
continue # 如果 URL 已处理,则跳过
processed_urls.add(url) # 标记为已处理
if len(processed_urls) == 1:
# 第一次需要用户确认
input(f"准备打开网页: {url},按回车键继续...")
driver.get(url)
print(f"打开网页: {url}")
# 等待页面加载
time.sleep(3)
# 滚动页面3次
for _ in range(3):
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
time.sleep(3)
driver.execute_script("window.scrollTo(0, 0);")
time.sleep(3)
# 生成文件名,取最后一个/后的10位字符
file_name_part = url.split('/')[-1][-10:] # 获取最后10个字符
file_name = f"{file_name_part}.qaqtools" # 添加后缀
file_path = os.path.join(save_folder, file_name)
# 保存网页
with open(file_path, 'w', encoding='utf-8') as f:
f.write(driver.page_source)
print(f"已保存网页为: {file_path}")
print("等待更新...")
time.sleep(120) # 每120秒检查一次新的 URLs
except pymysql.MySQLError as err:
print(f"数据库错误: {err}")
time.sleep(10)
except Exception as e:
print(f"发生错误: {e}")
time.sleep(10)
finally:
if cursor:
cursor.close()
if conn:
conn.close()
driver.quit() # 确保在结束时关闭WebDriver
if __name__ == "__main__":
clean_duplicates() # 先清除重复项
save_webpages() # 开始保存网页