FastAPI与Selenium:打造高效的Web数据抓取服务

时间:2025-02-06 17:14:48
# -*- coding: utf-8 -*- """ FastAPI与Selenium结合示例: 通过FastAPI提供API接口,使用Selenium进行网页抓取。 代码中配置了代理IP(参考亿牛云爬虫代理www.16yun.cn)、User-Agent和Cookie。 此示例访问 https://pixabay.com ,采集页面中的图片及其相关信息。 """ from fastapi import FastAPI from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.by import By import time app = FastAPI() def create_driver(): # 初始化Chrome选项 chrome_options = Options() # 设置User-Agent,模拟真实浏览器请求 user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " \ "(KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36" chrome_options.add_argument(f"user-agent={user_agent}") # 配置代理IP参数(参考亿牛云爬虫代理) proxy_host = "proxy.16yun.cn" # 代理域名 proxy_port = "8000" # 代理端口 proxy_user = "your_username" # 代理用户名 proxy_pass = "your_password" # 代理密码 # 拼接代理字符串,格式为:username:password@host:port proxy = f"{proxy_user}:{proxy_pass}@{proxy_host}:{proxy_port}" chrome_options.add_argument(f"--proxy-server=http://{proxy}") # 可选:如果需要无头模式(不打开浏览器窗口),取消下行注释 # chrome_options.add_argument("--headless") # 初始化Chrome WebDriver driver = webdriver.Chrome(options=chrome_options) # 预先访问目标网站,设置Cookie示例(Cookie需与目标域名匹配) driver.get("https://pixabay.com") driver.add_cookie({ "name": "example_cookie", # Cookie名称 "value": "cookie_value", # Cookie值 "domain": "pixabay.com" # Cookie对应的域名 }) return driver @app.get("/crawl") def crawl(): """ 接口说明: 该接口使用Selenium访问 https://pixabay.com 页面, 采集页面中所有图片的URL及其相关描述信息(通过alt属性提供), 并以JSON格式返回采集结果。 """ try: # 创建Selenium WebDriver实例 driver = create_driver() # 访问目标URL:Pixabay首页 driver.get("https://pixabay.com") # 等待页面加载(根据实际情况可调整等待时间) time.sleep(5) # 查找页面中所有的img标签元素 img_elements = driver.find_elements(By.TAG_NAME, "img") # 存储图片信息的列表 images_info = [] # 遍历所有图片元素,提取图片URL和描述信息(alt属性) for img in img_elements: src = img.get_attribute("src") alt = img.get_attribute("alt") # 如果图片URL不存在则跳过 if not src: continue images_info.append({ "src": src, "alt": alt }) except Exception as e: # 捕获异常并返回错误信息 return {"error": str(e)} finally: # 关闭浏览器,释放资源 driver.quit() return {"total_images": len(images_info), "images": images_info} # 启动FastAPI服务(在命令行中运行: uvicorn main:app --host 0.0.0.0 --port 8000) if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=8000)