import random
route = route_elem.text.strip() if route_elem else ""
# 提取产品详情链接
link_elem = item.find('a', href=True)
link = "https://kyfw.12306.cn" + link_elem['href'] if link_elem else ""
# 提取产品图片
img_elem = item.find('img', src=True)
img_url = img_elem['src'] if img_elem else ""
products.append({
'name': name,
'price': price,
'route': route,
'link': link,
'image_url': img_url,
'crawled_time': pd.Timestamp.now()
})
except Exception as e:
print(f"提取产品信息时出错: {e}")
continue
return products
def crawl_12306_tours():
"""爬取12306旅游产品的完整流程"""
print("启动浏览器(使用代理服务器)...")
print(f"代理服务器: {proxyHost}:{proxyPort}")
driver = setup_driver()
try:
# 访问12306旅游产品页面
print("访问12306旅游产品页面...")
driver.get("https://kyfw.12306.cn/otn/product/index.html")
# 等待页面加载
time.sleep(3)
# 检查并处理验证码
if handle_verification(driver):
# 验证码处理后重新等待页面加载
time.sleep(3)
# 提取产品信息
print("正在提取旅游产品信息...")
products = extract_tour_products(driver)
# 保存数据
if products:
df = pd.DataFrame(products)
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"12306_tours_{timestamp}.csv"
df.to_csv(filename, index=False, encoding='utf-8-sig')
print(f"成功提取 {len(products)} 个旅游产品,已保存到 {filename}")
# 同时保存JSON格式
json_filename = f"12306_tours_{timestamp}.json"
with open(json_filename, 'w', encoding='utf-8') as f:
json.dump(products, f, ensure_ascii=False, indent=2)
print(f"JSON数据已保存到 {json_filename}")
else:
print("未找到旅游产品信息")
return products
except Exception as e:
print(f"爬取过程中发生错误: {e}")
return []
finally:
# 关闭浏览器
driver.quit()
print("浏览器已关闭")
# 执行爬虫
if __name__ == "__main__":
crawl_12306_tours()


