使用selenium爬取淘宝网站信息使用scrapy和selenium实现对于用益信托网产品页(http://www.yanglee.com/Product/Index.aspx) 下所有信托产品明细信息部分字段的自动爬取。
时间: 2025-07-06 17:54:08 浏览: 3
### 使用 Selenium 和 Scrapy 实现用益信托网信托产品明细信息的爬取
#### 1. 安装依赖库
为了使用 Selenium 和 Scrapy 进行网页抓取,需要安装相应的 Python 库。
```bash
pip install selenium scrapy requests pandas
```
还需要下载并配置 WebDriver(例如 ChromeDriver),以便与浏览器交互。
#### 2. 初始化 Scrapy 项目
创建一个新的 Scrapy 项目来管理爬虫逻辑:
```bash
scrapy startproject trust_products
cd trust_products
```
#### 3. 编写 Spider 文件
在 `spiders` 目录下新建一个名为 `trust_spider.py` 的文件,并编写如下代码:
```python
import scrapy
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service as ChromeService
from webdriver_manager.chrome import ChromeDriverManager
import time
class TrustSpider(scrapy.Spider):
name = "trust"
allowed_domains = ["yanglee.com"]
start_urls = ['http://www.yanglee.com/Product/Index.aspx']
def __init__(self, *args, **kwargs):
super(TrustSpider, self).__init__(*args, **kwargs)
options = webdriver.ChromeOptions()
options.add_argument('--headless') # 设置无头模式
service = ChromeService(executable_path=ChromeDriverManager().install())
self.driver = webdriver.Chrome(service=service, options=options)
def parse(self, response):
self.driver.get(response.url)
time.sleep(5) # 等待页面加载完成
while True:
try:
elements = self.driver.find_elements(By.CSS_SELECTOR, 'a.product-link')
for element in elements:
product_id = element.get_attribute('data-id')
detail_url = f"http://www.yanglee.com/Product/Detail/{product_id}"
yield scrapy.Request(detail_url, callback=self.parse_detail)
next_button = self.driver.find_element(By.CSS_SELECTOR, '.next-page-button')
if not next_button.is_enabled():
break
next_button.click()
time.sleep(5) # 等待新一页加载
except Exception as e:
print(f"Error occurred: {str(e)}")
break
def parse_detail(self, response):
item = {}
title = response.css('.title::text').get()
description = response.css('.description p::text').getall()
details = response.css('.details td::text').getall()
item['title'] = title.strip() if title else None
item['description'] = '\n'.join([desc.strip() for desc in description]) if description else None
item['details'] = dict(zip(details[0::2], details[1::2])) if details else {}
yield item
```
此脚本实现了以下功能:
- 启动带有无头选项的 Chrome 浏览器实例。
- 访问起始 URL 并等待页面完全加载。
- 提取每页中的所有产品链接及其 ID 值[^1]。
- 对于每个产品详情页发起请求以获取更多信息。
- 处理分页机制直到没有更多可点击的“下一页”按钮为止。
- 解析具体的产品详情并将提取的信息作为字典返回给 Scrapy 引擎处理。
#### 4. 配置中间件
为了让 Scrapy 能够识别由 Selenium 返回的内容,在项目的 settings.py 中添加自定义 Downloader Middleware:
```python
DOWNLOADER_MIDDLEWARES = {
'scrapy_selenium.SeleniumMiddleware': 800,
}
```
同时确保已安装 `scrapy-selenium` 插件:
```bash
pip install scrapy-selenium
```
#### 5. 执行爬虫任务
最后运行命令启动爬虫程序:
```bash
scrapy crawl trust -o output.json
```
这会将所有的信托产品信息保存至 JSON 文件中供后续分析使用。
阅读全文