Advertisement

练习使用Scrapy爬取当当网商品数据

阅读量:

目标站点:”http://category.dangdang.com/pg1-cp01.54.04.00.00.00.html

需求数据:商品标题、链接、价格、评论数

要求:实现自动翻页并自动写如数据库

第一步 在项目文件夹下打开终端,使用一下命令创建项目。

复制代码
    scrapy startproject dangdang

第二部 创建爬虫文件

复制代码
    scrapy genspider -t basic ddts dangdang.com

第三步 在items文件下写入即将要爬的内容

复制代码
 title = scrapy.Field()

    
 link = scrapy.Field()
    
 price = scrapy.Field()
    
 comment = scrapy.Field()

第四步 编写爬虫文件

首先我们打开网页,在源代码里面找到定位元素,然后编写爬取规则,下面是我的代码

复制代码
 item["title"] = response.xpath("//a[@name='itemlist-title']/@title").extract()

    
 item["link"] = response.xpath("//a[@name='itemlist-title']/@href").extract()
    
 item["price"] = response.xpath("//span[@class='search_now_price']/text()").extract()
    
 item["comment"] = response.xpath("//a[@name='itemlist-review']/text()").extract()
    
 yield item
    
 # 实现翻页
    
 for i in range(2,101):
    
     url = "http://category.dangdang.com/pg" + str(i) + "-cp01.54.04.00.00.00.html"
    
     yield Request(url, callback=self.parse)

第五步 编写pipelines

复制代码
 class DangdangPipeline(object):

    
     def process_item(self, item, spider):
    
     conn = pymysql.connect(host='155.94.140.40',user='root',passwd='qq726819gzq.',db='dangdang',charset='utf8')
    
     for i in range(0, len(item["title"])):
    
         title = item["title"][i]
    
         link = item["link"][i]
    
         price = item["price"][i]
    
         comment = item['comment'][i]
    
         sql = "insert into book(title, link, price, comment) values('"+title+"','"+link+"','"+price+"','"+comment+"')"
    
         # print(title+'\n'+link+'\n'+price+'\n'+comment+'\n'+'------')
    
         conn.query(sql)
    
         conn.commit()
    
     conn.close()
    
     return item

这一步在设置数据库的时候注意改变数据库的的编码方式为utf8😭

新手练习,请大佬多多指点🙃

全部评论 (0)

还没有任何评论哟~