scrapy框架的爬蟲(chóng)demo

目的是爬取Weight Loss里面的文章慌洪。(自己寫(xiě)報(bào)告用勾徽,不宜作為學(xué)習(xí))

內(nèi)容包括{標(biāo)題泰涂,副標(biāo)題叔收,作者啄刹,頭像乙墙,日期颠锉,圖片拼卵,正文}

不多bb直接上代碼嗷嗷蓖议,scrapy框架的代碼應(yīng)該都是這樣吧


mySpider.py
import scrapy

from demo.itemsimport WeightItem

from bs4import UnicodeDammit

from bs4import BeautifulSoup

from urllib.requestimport urlopen

class MySpider(scrapy.Spider):

name="mySpider"

? ? source_url ='https://www.womenshealthmag.com/weight-loss/'

? ? def start_requests(self):

url = MySpider.source_url

yield scrapy.Request(url=url, callback=self.parse)

print("發(fā)送請(qǐng)求")

def parse(self, response):

i=0

? ? ? ? try:

dammit = UnicodeDammit(response.body, ["utf-8", "gbk"])

data = dammit.unicode_markup

selector = scrapy.Selector(text=data)

print("收到源代碼")

links = selector.xpath("http://div[position()>2][starts-with(@class,'simple-item grid-simple-item ')]/a[@class='simple-item-image item-image']")

print("主頁(yè)xpath")

for linkin links:

newslink = link.xpath("./@href").extract_first()

yield scrapy.Request(url=MySpider.source_url + newslink, callback=self.parse1)

except Exception as err:

print(err)

def parse1(self,response):

dammit = UnicodeDammit(response.body, ["utf-8", "gbk"])

data = dammit.unicode_markup

selector = scrapy.Selector(text=data)

text = selector.xpath("http://p[@class='body-text']/text()").extract()

text ="\n".join(text)

#text = selector.xpath("http://p[@class='body-text']/text()")[0]

#text = text.xpath("string(.)")

? ? ? ? ? ? ? ? pic = selector.xpath("/html/body/div[2]/div[4]/div[1]/div[1]/div/img/@data-src").extract_first()

header = selector.xpath("http://header[@class='content-header standard-header']/div[@class='content-header-inner']")

title = header.xpath(".//h1/text()").extract_first()

subtitle = header.xpath(".//p/text()").extract_first()

profilephoto = header.xpath(".//img/@data-src").extract_first()

author = header.xpath(".//span[@class='byline-name']/text()").extract_first()

date = header.xpath(".//time[@class='content-info-date']/text()").extract_first()

item = WeightItem()

item["title"] = title.strip()if titleelse ""

? ? ? ? ? ? ? ? item["subtitle"] = subtitle.strip()if subtitleelse ""

? ? ? ? ? ? ? ? item["author"] = author.strip()if authorelse ""

? ? ? ? ? ? ? ? item["date"] = date.strip()if dateelse ""

? ? ? ? ? ? ? ? item["profilephoto"] = profilephoto.strip()if profilephotoelse ""

? ? ? ? ? ? ? ? item["text"] = text.strip()if textelse ""

? ? ? ? ? ? ? ? item["pic"] = pic.strip()if picelse ""

? ? ? ? ? ? ? ? yield item


item.py

import scrapy

class WeightItem(scrapy.Item):

# define the fields for your item here like:

# name = scrapy.Field()

? ? title = scrapy.Field()

subtitle=scrapy.Field()

author = scrapy.Field()

date = scrapy.Field()

profilephoto=scrapy.Field()

text = scrapy.Field()

pic=scrapy.Field()


piplines.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 pymysql

class WeightPipeline(object):

def open_spider(self, spider):

print("開(kāi)始")

try:

self.con = pymysql.connect(host="127.0.0.1",

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? port=3306,

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? user="root",

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? passwd="密碼",

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? charset="utf8"

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? )

self.cursor =self.con.cursor(pymysql.cursors.DictCursor)

print("已連接到mysql")

try:

self.cursor.execute("create database mydb")

print("創(chuàng)建新的數(shù)據(jù)庫(kù)")

except:

pass

? ? ? ? ? ? self.con.select_db("mydb")

try:

self.cursor.execute("drop table Woman'sHealth")

print("刪除原來(lái)的表")

except:

pass

? ? ? ? ? ? try:

sql ="""

create table WomansHealth(

Id varchar(8) primary key,

Title varchar(512) ,

Subtitle varchar(256),

Profilephoto varchar(256),

Author varchar(64),

Date varchar(16),

Text text,

Pic varchar(256))

"""

? ? ? ? ? ? ? ? self.cursor.execute(sql)

print("創(chuàng)建新的表")

except:

self.cursor.execute("delete from WomansHealth")

self.opened =True

? ? ? ? ? ? self.count =0

? ? ? ? except Exception as err:

print(err)

self.opened =False

? ? def close_spider(self, spider):

if self.opened:

self.con.commit()

self.con.close()

self.opened =False

? ? ? ? print("closed")

print(self.count)# 無(wú)法顯示

? ? def process_item(self, item, spider):

try:

print("----------------------")

print("標(biāo)題:"+item["title"])

print("副標(biāo)題:"+item["subtitle"])

print("作者:"+item["author"])

print("日期:"+item["date"])

print("頭像鏈接:"+item["profilephoto"])

print("正文:"+item["text"])

print("圖片鏈接:"+item["pic"])

print("---------------------")

if self.opened:

self.count +=1

? ? ? ? ? ? ? ? print(self.count)

ID =str(self.count)

while len(ID) <8:

ID ="0"+ID

self.cursor.execute(

"insert into WomansHealth(Id,Title,Subtitle,Profilephoto,Author,Date,Text,Pic) values (%s,%s,%s,%s,%s,%s,%s,%s)",

? ? ? ? ? ? ? ? ? ? (ID, item["title"], item["subtitle"],item["profilephoto"], item["author"], item["date"], item["text"], item["pic"]))

except Exception as err:

print(err)

return item


run.py

from scrapyimport cmdline

cmdline.execute("scrapy crawl mySpider -s LOG_ENABLED=False".split())


setting.py 里面加一句
ITEM_PIPELINES = {

'demo.pipelines.WeightPipeline':300, }


然后就存到數(shù)據(jù)庫(kù)了

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末虏杰,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子勒虾,更是在濱河造成了極大的恐慌纺阔,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,451評(píng)論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件修然,死亡現(xiàn)場(chǎng)離奇詭異笛钝,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)愕宋,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,172評(píng)論 3 394
  • 文/潘曉璐 我一進(jìn)店門(mén)玻靡,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人中贝,你說(shuō)我怎么就攤上這事啃奴。” “怎么了雄妥?”我有些...
    開(kāi)封第一講書(shū)人閱讀 164,782評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵最蕾,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我老厌,道長(zhǎng)瘟则,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,709評(píng)論 1 294
  • 正文 為了忘掉前任枝秤,我火速辦了婚禮醋拧,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘淀弹。我一直安慰自己丹壕,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,733評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布薇溃。 她就那樣靜靜地躺著菌赖,像睡著了一般。 火紅的嫁衣襯著肌膚如雪沐序。 梳的紋絲不亂的頭發(fā)上琉用,一...
    開(kāi)封第一講書(shū)人閱讀 51,578評(píng)論 1 305
  • 那天堕绩,我揣著相機(jī)與錄音,去河邊找鬼邑时。 笑死奴紧,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的晶丘。 我是一名探鬼主播黍氮,決...
    沈念sama閱讀 40,320評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼浅浮!你這毒婦竟也來(lái)了滤钱?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 39,241評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤脑题,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后铜靶,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體叔遂,經(jīng)...
    沈念sama閱讀 45,686評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,878評(píng)論 3 336
  • 正文 我和宋清朗相戀三年争剿,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了已艰。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,992評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡蚕苇,死狀恐怖哩掺,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情涩笤,我是刑警寧澤嚼吞,帶...
    沈念sama閱讀 35,715評(píng)論 5 346
  • 正文 年R本政府宣布,位于F島的核電站蹬碧,受9級(jí)特大地震影響舱禽,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜恩沽,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,336評(píng)論 3 330
  • 文/蒙蒙 一誊稚、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧罗心,春花似錦里伯、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,912評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至飒箭,卻和暖如春爷贫,著一層夾襖步出監(jiān)牢的瞬間认然,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,040評(píng)論 1 270
  • 我被黑心中介騙來(lái)泰國(guó)打工漫萄, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留卷员,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,173評(píng)論 3 370
  • 正文 我出身青樓腾务,卻偏偏與公主長(zhǎng)得像毕骡,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子岩瘦,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,947評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容