首页 > 其他分享 >今日总结

今日总结

时间:2024-03-26 21:35:41浏览次数:22  
标签:总结 comment self item scrapy 今日 div class

在开始编写爬虫程序之前,我们需要先分析目标网站的结构和数据。在本文中,我们选择抓取京东商城的商品信息、价格、评论等数据。

1.商品信息
商城的商品信息包括商品名称、商品编号、商品分类、商品品牌、商品型号、商品规格、商品产地、商品重量、商品包装等信息。这些信息可以在商品详情页面中找到。

价格
商城的商品价格包括商品原价、商品促销价、商品折扣等信息。这些信息可以在商品详情页面中找到。

评论
京东商城的商品评论包括用户评价、用户晒图、用户追评等信息。这些信息可以在商品详情页面中找到。

三、编写爬虫程序
在分析目标网站的结构和数据之后,我们可以开始编写爬虫程序了。在本文中,我们使用Scrapy框架编写爬虫程序,将抓取到的数据保存到MySQL数据库中。

创建Scrapy项目
首先,我们需要创建一个Scrapy项目。在命令行中输入以下命令:

scrapy startproject jingdong
1
这将创建一个名为jingdong的Scrapy项目。

创建爬虫
接下来,我们需要创建一个爬虫。在命令行中输入以下命令:

scrapy genspider jingdong_spider jd.com
1
这将创建一个名为jingdong_spider的爬虫,爬取的网站为jd.com。

编写爬虫代码
在创建完爬虫之后,我们需要编写爬虫代码。在Scrapy框架中,爬虫代码主要包括以下几个部分:

(1)定义Item

Item是Scrapy框架中的一个概念,它用于定义要抓取的数据结构。在本文中,我们需要定义一个Item,用于保存商品信息、价格、评论等数据。在项目的items.py文件中,添加以下代码:

import scrapy

class JingdongItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
name = scrapy.Field()
sku = scrapy.Field()
category = scrapy.Field()
brand = scrapy.Field()
model = scrapy.Field()
spec = scrapy.Field()
origin = scrapy.Field()
weight = scrapy.Field()
package = scrapy.Field()
price = scrapy.Field()
promotion_price = scrapy.Field()
discount = scrapy.Field()
comment = scrapy.Field()
image_urls = scrapy.Field()
images = scrapy.Field()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
这里定义了一个名为JingdongItem的Item,包括商品名称、商品编号、商品分类、商品品牌、商品型号、商品规格、商品产地、商品重量、商品包装、商品价格、商品促销价、商品折扣、商品评论、商品图片等字段。

(2)编写爬虫代码
在项目的spiders目录下,打开jingdong_spider.py文件,添加以下代码:

import scrapy
from jingdong.items import JingdongItem

class JingdongSpider(scrapy.Spider):
name = 'jingdong'
allowed_domains = ['jd.com']
start_urls = ['https://www.jd.com/']

def parse(self, response):
# 获取所有分类链接
category_links = response.xpath('//div[@class="category-item"]/div[@class="item-list"]/ul/li/a/@href')
for link in category_links:
yield scrapy.Request(link.extract(), callback=self.parse_category)

def parse_category(self, response):
# 获取所有商品链接
product_links = response.xpath('//div[@class="gl-i-wrap"]/div[@class="p-img"]/a/@href')
for link in product_links:
yield scrapy.Request(link.extract(), callback=self.parse_product)

# 获取下一页链接
next_page_link = response.xpath('//a[@class="pn-next"]/@href')
if next_page_link:
yield scrapy.Request(next_page_link.extract_first(), callback=self.parse_category)

def parse_product(self, response):
item = JingdongItem()

# 获取商品名称
item['name'] = response.xpath('//div[@class="sku-name"]/text()')[0].extract()

# 获取商品编号
item['sku'] = response.xpath('//div[@class="itemInfo-wrap"]/div[@class="clearfix"]/div[@class="sku"]/div[@class="item"]/div[@class="name"]/text()')[0].extract()

# 获取商品分类
category_list = response.xpath('//div[@class="breadcrumb"]/a/text()')
item['category'] = '>'.join(category_list.extract())

# 获取商品品牌
item['brand'] = response.xpath('//div[@class="itemInfo-wrap"]/div[@class="clearfix"]/div[@class="sku-name"]/a/@title')[0].extract()

# 获取商品型号
item['model'] = response.xpath('//div[@class="Ptable"]/div[@class="Ptable-item"]/dl/dt/text()')[0].extract()

# 获取商品规格
spec_list = response.xpath('//div[@class="Ptable"]/div[@class="Ptable-item"]/dl/dd/ul/li/text()')
item['spec'] = ','.join(spec_list.extract())

# 获取商品产地
item['origin'] = response.xpath('//div[@class="Ptable"]/div[@class="Ptable-item"]/dl/dd/text()')[0].extract()

# 获取商品重量
item['weight'] = response.xpath('//div[@class="Ptable"]/div[@class="Ptable-item"]/dl/dd/text()')[1].extract()

# 获取商品包装
item['package'] = response.xpath('//div[@class="Ptable"]/div[@class="Ptable-item"]/dl/dd/text()')[2].extract()

# 获取商品价格
price_list = response.xpath('//div[@class="summary-price-wrap"]/div[@class="summary-price J-summary-price"]/div[@class="dd"]/span/text()')
item['price'] = price_list[0].extract()
item['promotion_price'] = price_list[1].extract() if len(price_list) > 1 else ''
item['discount'] = response.xpath('//div[@class="summary-price-wrap"]/div[@class="summary-price J-summary-price"]/div[@class="dd"]/div[@class="promo"]/span/text()')[0].extract()

# 获取商品评论
comment_list = response.xpath('//div[@class="comment-item"]')
comment_text_list = []
for comment in comment_list:
comment_text = comment.xpath('div[@class="comment-column J-comment-column"]/div[@class="comment-con"]/div[@class="comment-con-top"]/div[@class="comment-con-txt"]/text()').extract_first()
if comment_text:
comment_text_list.append(comment_text.strip())
item['comment'] = '\n'.join(comment_text_list)

# 获取商品图片
item['image_urls'] = response.xpath('//div[@class="spec-items"]/ul/li/img/@src')
item['images'] = []

yield item

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
这里定义了一个名为JingdongSpider的爬虫,首先获取所有分类链接,然后依次访问每个分类页面,获取所有商品链接,然后依次访问每个商品页面,抓取商品信息、价格、评论等数据,并保存到Item中。

(3)配置数据库

在项目的settings.py文件中,添加以下代码:

ITEM_PIPELINES = {
'jingdong.pipelines.JingdongPipeline': 300,
}

MYSQL_HOST = 'localhost'
MYSQL_PORT = 3306
MYSQL_USER = 'root'
MYSQL_PASSWORD = '123456'
MYSQL_DBNAME = 'jingdong'
1
2
3
4
5
6
7
8
9
这里定义了一个名为JingdongPipeline的管道,用于将抓取到的数据保存到MySQL数据库中。同时,配置了MySQL数据库的连接信息。

(4)编写管道代码

在项目的pipelines.py文件中,添加以下代码:

import pymysql
from scrapy.exceptions import DropItem
from scrapy.pipelines.images import ImagesPipeline
from jingdong.items import JingdongItem

class JingdongPipeline(object):
def __init__(self, host, port, user, password, dbname):
self.host = host
self.port = port
self.user = user
self.password = password
self.dbname = dbname

@classmethod
def from_crawler(cls, crawler):
return cls(
host=crawler.settings.get('MYSQL_HOST'),
port=crawler.settings.get('MYSQL_PORT'),
user=crawler.settings.get('MYSQL_USER'),
password=crawler.settings.get('MYSQL_PASSWORD'),
dbname=crawler.settings.get('MYSQL_DBNAME')
)

def open_spider(self, spider):
self.conn = pymysql.connect(host=self.host, port=self.port, user=self.user, password=self.password, db=self.dbname, charset='utf8')
self.cursor = self.conn.cursor()

def close_spider(self, spider):
self.conn.close()

def process_item(self, item, spider):
if not isinstance(item, JingdongItem):
return item

# 保存商品信息
sql = 'INSERT INTO product(name, sku, category, brand, model, spec, origin, weight, package, price, promotion_price, discount, comment) VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)'
self.cursor.execute(sql, (item['name'], item['sku'], item['category'], item['brand'], item['model'], item['spec'], item['origin'], item['weight'], item['package'], item['price'], item['promotion_price'], item['discount'], item['comment']))
product_id = self.cursor.lastrowid

# 保存商品图片
if item['image_urls']:
for image_url in item['image_urls']:
self.cursor.execute('INSERT INTO image(product_id, url) VALUES(%s, %s)', (product_id, image_url))
self.conn.commit()

return item

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
这里定义了一个名为JingdongPipeline的管道,用于将抓取到的数据保存到MySQL数据库中。在process_item方法中,首先保存商品信息到product表中,然后保存商品图片到image表中。

(5)配置图片下载

在项目的settings.py文件中,添加以下代码:

ITEM_PIPELINES = {
'jingdong.pipelines.JingdongPipeline': 300,
'scrapy.pipelines.images.ImagesPipeline': 1,
}

IMAGES_STORE = 'images'
1
2
3
4
5
6
这里配置了图片下载的管道和存储路径。

(6)运行爬虫

在命令行中输入以下命令,运行爬虫:

scrapy crawl jingdong
1
这将启动爬虫程序,开始抓取京东商城的商品信息、价格、评论等数据,并保存到MySQL数据库中。

标签:总结,comment,self,item,scrapy,今日,div,class
From: https://www.cnblogs.com/zhaoyueheng/p/18097617

相关文章

  • Div4 VP总结
    CodeforcesRound799(Div.4)E(最长子区间)基本思路求满足s的最长子区间。错误思路分析想用双指针左右贪心模拟题目要求删前或后的数(但在面对前后两个相等的时候,删前删后没有无后效性)简单暴力枚举子区间长度(显然在n=1e5的时候t了)正确思路虽然也是暴力枚举子区间,但有做......
  • MySQL大总结(1)
    1.关系型数据库的特点     1、使用表来存储数据,格式统一,便于维护。2、使用SQL语句操作数据库,标准统一,使用方便。3、数据存储在磁盘中,相对安全。2.DBMS、数据库和表的关系?简言之,先有DBMS,之后有数据库,再有表,每个表中再有数据,具体如下图所示。3.以下关于连接My......
  • Shellcode注入总结
    Shellcode注入总结6x0远程线程注入dll通过在其他进程创建一个远程线程,执行我们的shellcode加载器dll效果:目前dll的shellcode加载器使用了远程加载,能大概绕过火绒静动态,defender的静态。360动静态全杀6x0x0直接看注入exe代码:#include<iostream>#include<tchar.h>#in......
  • 20240324比赛总结
    T1卫星照片https://gxyzoj.com/d/hzoj/p/3657bfs暴力找联通块,再暴力判断即可因为某些原因代码丢了,就不放了T2[luogu3802]小魔女帕琪https://gxyzoj.com/d/hzoj/p/3656考虑到,前7个均不同的概率为\(\prod_{i=1}^{7}\dfrac{a_i}{sum+1-i}\times7!\)因为每种情况均有\(\pro......
  • Android开发两年,我要跳槽去阿里巴巴了,做个阶段总结
    Host:www.baidu.comContent-Type:text/plain//Body搜索****2)响应报文//状态行(包括HTTP版本、状态码,状态信息)HTTP/1.1200OK//HeadersContent-Type:application/json;charset=utf-8//Body[{“info”:“xixi”}]3)常用状态码主要分为五种类型:1开头,代表临时......
  • 3. 文件上传漏洞——漏洞总结笔记
    一、文件上传漏洞前提条件:能上传webshell(若仅让上传图片,而又绕不过去,则不行)webshell路径可知(需要访问目标,不知道则访问不了)webshell 可以被访问webshell可以被解析(即可以显示页面;若返回页面直接显示代码,并没有解析)判断确认是什么过滤?上传任意......
  • FPGA亚稳态学习总结
     首先是组合逻辑电路考虑的是竞争冒险,冒险会产生毛刺。重点研究如何去毛刺时序逻辑电路考虑的是时序不满足会产生的亚稳态问题:如何考量时序满不满足呢?根据不同的场景又有不同的说法。时序分析的两组基本概念建立时间与保持时间1.在同步系统和异步系统(跨时钟域传输)中有两个......
  • 攻防中的信息收集总结
    1.公司查询备案号能拿到公司最直接的域名信息工信部的ICP备案查询系统:https://beian.miit.gov.cn/#/Integrated/recordQuery爱企查,企查查收集关系图谱、企业图谱whois查询http://whois.chinaz.com/https://whois.aizhan.com/enscan工具个人觉得非常不错的收集子公......
  • 【SpringBoot3+Mybatis】小程序和后台管理系统 员工/分类/菜品/套餐管理 上传文件 CRU
    文章目录一、项目介绍&Github二、技术选型三、开发环境搭建四、员工管理4.1新增员工①sql②对象拷贝DTO与Entity③异常捕获与处理④动态获取当前登录者Id⑤ThreadLocal4.2员工分页查询①请求参数实体与响应数据实体②controller层③service层使用pageHelper......
  • 数学分析基本定义定理总结
    数学分析中的重要概念与定理一、实数集完备性基本定理实数稠密性Archimedes性实数集基本定理确界原理:非空有界数集有上/下界则必有上/下确界上确界/下确界单调有界定理:单调有界数列必有极限区间套定理:实数系中存在唯一一点包含在闭区间套的所有闭区间之中......