scrapy爬取jd
时间: 2025-01-18 09:10:44 浏览: 52
### 使用Scrapy框架爬取京东网站商品信息数据
#### 创建项目并配置环境
创建一个新的Scrapy项目用于爬取京东商品信息。通过命令行工具执行如下操作:
```bash
scrapy startproject jd_spider
cd jd_spider
```
这会初始化一个名为`jd_spider`的新目录,其中包含了Scrapy项目的默认文件结构。
#### 定义Item类
在`items.py`中定义所需抓取的数据字段,例如商品名称、价格等基本信息。以下是简单的示例代码片段:
```python
import scrapy
class JdSpiderItem(scrapy.Item):
product_name = scrapy.Field() # 商品名
price = scrapy.Field() # 单价
link = scrapy.Field() # 链接地址
shop_name = scrapy.Field() # 店铺名字
```
此部分设置决定了最终能够从网页上抽取哪些具体的内容[^1]。
#### 编写Spiders脚本
进入spiders子文件夹下新建Python模块文件如`jd_product.py`,在此处编写具体的爬虫逻辑。下面给出一段简化版的蜘蛛代码作为参考:
```python
import scrapy
from ..items import JdSpiderItem
class JDProductSpider(scrapy.Spider):
name = "jd_products"
allowed_domains = ["search.jd.com"]
def __init__(self, keyword=None, pages=10, *args, **kwargs):
super(JDProductSpider, self).__init__(*args, **kwargs)
base_url = 'https://search.jd.com/Search?keyword={}&enc=utf-8&page='
self.start_urls = [base_url.format(keyword)+str(i*2+1) for i in range(int(pages))]
def parse(self, response):
items = []
selector_list = response.xpath('//li[@class="gl-item"]')
for sel in selector_list:
item = JdSpiderItem()
try:
item['product_name'] = ''.join(sel.xpath('.//div[contains(@class,"p-name")]/a/em/text()').extract()).strip().replace('\n', '')
item['price'] = sel.css('i::text').get()
item['link'] = 'http:' + sel.xpath('.//div[@class="p-img"]/a/@href').get()
item['shop_name'] = sel.xpath('.//span[@class="J_im_icon"]/a/text()').get()
yield item
except Exception as e:
print(e)
next_page = response.css('a.pn-next::attr(href)').get()
if next_page is not None:
yield response.follow(next_page, callback=self.parse)
```
这段代码实现了启动命令接收两个参数——关键词和页数,并据此构建起始链接列表;解析每一页中的商品条目,提取目标属性填充至自定义item对象内;最后尝试跟进分页按钮继续访问后续页面直至结束。
#### 数据管道Pipeline设定
编辑settings.py开启pipelines功能并将收集到的结果存入MySQL数据库中。这里假设已经安装好相应的驱动库并且完成了必要的表单建模工作:
```python
ITEM_PIPELINES = {
'jd_spider.pipelines.JdSpiderPipeline': 300,
}
```
接着,在pipelines.py里补充实际入库的方法实现细节:
```python
import pymysql.cursors
class JdSpiderPipeline(object):
def open_spider(self, spider):
db_config = getattr(spider.settings,'DB_CONFIG',{
'host':'localhost',
'port':3306,
'user':'root',
'password':'your_password',
'db':'test_db'
})
self.conn = pymysql.connect(**db_config)
with self.conn.cursor() as cursor:
sql_create_table='''
CREATE TABLE IF NOT EXISTS products(
id INT AUTO_INCREMENT PRIMARY KEY ,
product_name VARCHAR(255),
price DECIMAL(10 , 2 ),
link TEXT,
shop_name VARCHAR(255))
'''
cursor.execute(sql_create_table)
def process_item(self, item, spider):
insert_sql="""
INSERT INTO `products`(product_name,price,link,shop_name)
VALUES (%s,%s,%s,%s);
"""
data_tuple=(item["product_name"],float(item["price"]),item["link"],item["shop_name"])
with self.conn.cursor() as cursor:
cursor.execute(insert_sql,data_tuple)
return item
def close_spider(self, spider):
self.conn.commit()
self.conn.close()
```
以上即为完整的基于Scrapy框架针对京东平台的商品详情数据采集方案概述。
阅读全文
相关推荐
















