日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

我的第一个Scrapy 程序 - 爬取当当网信息

發(fā)布時間:2025/4/5 编程问答 20 豆豆
生活随笔 收集整理的這篇文章主要介紹了 我的第一个Scrapy 程序 - 爬取当当网信息 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

前面已經安裝了Scrapy,下面來實現(xiàn)第一個測試程序。

概述

Scrapy是一個爬蟲框架,他的基本流程如下所示(下面截圖來自互聯(lián)網)

簡單的說,我們需要寫一個item文件,定義返回的數據結構;寫一個spider文件,具體爬取的數據程序,以及一個管道 pipeline 文件,作為后續(xù)操作,比如保存數據等等。

下面以當當網為例,看看怎么實現(xiàn)。
這個例子里面我想爬取的內容是前面20頁的羽絨服產品,包括產品名字,鏈接和評論數。

過程

1. 創(chuàng)建一個Scrapy的項目

scrapy startproject dangdang

2. 創(chuàng)建一個爬蟲文件**

scrapy genspider -t basic dd dangdang.com

這樣他會自動創(chuàng)建一個爬蟲文件,結構如下所示:

3. 編寫items.py

items.py

# -*- coding: utf-8 -*-# Define here the models for your scraped items # # See documentation in: # https://doc.scrapy.org/en/latest/topics/items.htmlimport scrapyclass DangdangItem(scrapy.Item):# define the fields for your item here like:# name = scrapy.Field()title=scrapy.Field()url=scrapy.Field()comment=scrapy.Field()

4. 編寫爬蟲文件dd.py

前面第二步已經自動生成了一個模板,我們直接修改就行。
dd.py

# -*- coding: utf-8 -*-import scrapy from dangdang.items import DangdangItem from scrapy.http import Requestclass DdSpider(scrapy.Spider):name = 'dd'allowed_domains = ['dangdang.com']start_urls = ['http://category.dangdang.com/pg1-cid4010275.html']def parse(self, response):item=DangdangItem()item['title']=response.xpath(u"//a[@dd_name='單品標題']/text()").extract()item['url']=response.xpath("//a[@dd_name='單品標題']/@href").extract()item['comment']=response.xpath("//a[@dd_name='單品評論']/text()").extract()text = response.body# content_type = chardet.detect(text)# if content_type['encoding'] != 'UTF-8':# text = text.decode(content_type['encoding'])# text = text.encode('utf-8')# print(text)yield itemfor i in range(2,20):url='http://category.dangdang.com/pg%d-cid4010275.html'%iyield Request(url,callback=self.parse)

5. 編寫pipelines.py

為了使用pipeline,配置文件需要做個小修改,我順便關掉了對robot文件的確認
settings.py

ROBOTSTXT_OBEY = FalseITEM_PIPELINES = {'dangdang.pipelines.DangdangPipeline': 300, }

pipeline.py

# -*- coding: utf-8 -*-# Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html import pymysqlclass DangdangPipeline(object):def process_item(self, item, spider):conn=pymysql.connect(host='127.0.0.1',user='root',passwd='root',db='dangdang',use_unicode=True,charset='utf8')for i in range(0,len(item['title'])):title=item['title'][i]link=item['url'][i]comment=item['comment'][i]print(type(title))print(title)# sql="insert into dd(title,link,comment) values ('"+title+"','"+link+"','"+comment+"')"sql = "insert into dd(title,link,comment) values('" + title + "','" + link + "','" + comment + "')"try:conn.query(sql)except Exception as err:passconn.close()return item

6. 創(chuàng)建數據庫和表

我最后的數據要保存到mysql里面,python里面可以通過pymysql進行操作。我提前在mysql命令行界面里面創(chuàng)建了一個數據庫和空表

mysql> create database dangdang; mysql> create table dd(id int auto_increment primary, title varchar(100), link varchar(100), comment varchar(32));

7. 執(zhí)行

scrapy crawl dd
如果不想看日志 可以使用
scrapy crawl dd --nolog

8. 檢測結果

test.py

#!/usr/bin/env python #! -*- coding:utf-8 -*- # Author: Yuan Li import pymysql conn=pymysql.connect(host='127.0.0.1',user='root',passwd='root',db='dangdang',use_unicode=True,charset='utf8')cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) #SQL查詢 cursor.execute("select * from dd") row=cursor.fetchall() for i in row:print(i) conn.close()

結果測試成功

轉載于:https://blog.51cto.com/beanxyz/2069239

總結

以上是生活随笔為你收集整理的我的第一个Scrapy 程序 - 爬取当当网信息的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。