items.py
# -*- coding: utf-8 -*-
# define here the models for your scraped items
## see documentation in:
# import scrapy
class
mkwitem
(scrapy.item)
: link = scrapy.field()#
type
= scrapy.field(
)# 屬於
title = scrapy.field(
)# 標題
level = scrapy.field(
)# 級別
num = scrapy.field(
)# 人數
info = scrapy.field(
)# 簡介
price = scrapy.field(
)# **
spiders/**.py
# -*- coding: utf-8 -*-
import scrapy
from..
import items
class
mukespider
(scrapy.spider)
: name =
'muke'
allowed_domains =
['imooc.com'
] start_urls =
['']def
parse
(self, response)
: item = items.mkwitem(
)for i in
range
(len
(response.xpath(
'//*[@id="main"]/div[2]/div[2]/div[1]/div/div'))
):long
= response.xpath(
'//*[@id="main"]/div[2]/div[2]/div[1]/div/div[{}]'
.format
(i +1)
) item[
'link']=
long
.xpath(
'.//a/div[1]/img/@data-original'
).extract()[
0]type_l =
''for i in
long
.xpath(
'.//a/div[1]/div/label/text()'
).extract():
type_l = type_l + i +
'+' item[
'type'
]= type_l
item[
'title']=
long
.xpath(
'.//a/div[2]/h3/text()'
).extract()[
0]item[
'level']=
long
.xpath(
'.//a/div[2]/div/div[1]/span[1]/text()'
).extract()[
0]item[
'num']=
long
.xpath(
'.//a/div[2]/div/div[1]/span[2]/text()'
).extract()[
0]item[
'info']=
long
.xpath(
'.//a/div[2]/div/p/text()'
).extract()[
0]item[
'price']=
long
.xpath(
'.//a/div[2]/div/div[2]/div/span/text()'
).extract()[
0]yield item
url = response.xpath(
).extract(
)if url:
page =
''+ url[0]
# 返回url
yield scrapy.request(page, callback=self.parse)
pipeline.py
# -*- coding: utf-8 -*-
import pymysql
class
mkwpipeline
(object):
def__init__
(self)
: self.connect = pymysql.connect(host=
'88.88.88.88'
, user=
'8888'
, passwd=
'8888'
, db=
'8888'
)# 後面三個依次是資料庫連線名、資料庫密碼、資料庫名稱
self.cursor = self.connect.cursor(
)def
process_item
(self, item, spider)
:# sql語句
insert_sql =
"insert into mkw(link, type, title, level, num, info, price) values (%s, %s, %s, %s, %s, %s, %s)"
# 執行插入資料到資料庫操作
self.cursor.execute(insert_sql,
( item[
'link'
], item[
'type'
], item[
'title'
], item[
'level'
], item[
'num'
], item[
'info'
], item[
'price'])
)# 提交,不進行提交無法儲存到資料庫
self.connect.commit(
)def
close_spider
(self, spider)
:# 關閉游標和連線
self.cursor.close(
) self.connect.close(
)
settings.py
user_agent =
robotstxt_obey =
false
concurrent_requests =
32download_delay =
0.1default_request_headers =
item_pipelines =
scrapy爬取資料並儲存到文字
1.scrapy專案結構如下 2.開啟spidler目錄下的duba.py檔案,如下 這個是根據豆瓣一部分頁面獲取的熱門話題內容,有6條資料 coding utf 8 import scrapy from scrapydemo.items import scrapydemoitem from lxm...
Scrapy爬取網頁並儲存到資料庫中
scrapy爬取網頁並儲存到資料庫中 一.新建乙個scrapy工程。進入乙個你想用來儲存 的資料夾,然後執行 t scrapy startproject fjsen 會生成一堆資料夾和檔案 scrapy.cfg 專案配置檔案 tutorial 專案python模組,呆會 將從這裡匯入 tutoria...
Scrapy爬取並儲存到TXT檔案
在建立完成專案並建立爬蟲的基礎上,編寫儲存到txt的專案 1.將 robotstxt obey 設定為false 2.將 item pipelines 開啟 item是scrapy提供的類似於字典型別的資料容器,它與字典最大的區別在於它規定了統一的資料規格樣式,即具有統一性與結構性。這樣既方便資料的...