python3 [爬蟲入門實戰]爬蟲之scrapy爬取中國醫學人才網
阿新 • • 發佈:2019-02-04
自己第一次試著用scrapy進行爬取網頁,總共爬下9240條資料,也就兩分鐘不到,400多頁吧。用的比較簡單,但是爬取成功後感覺成就感滿滿的。
來張爬取結果圖
爬取欄位:
“hospitalName”: “hospitalDesc”: “hospitalSize”:”hospitalAddress”:
1爬取欄位
這裡爬取的內容上面都有標註,只不過,爬取下來沒有儲存連結(稍微有點小遺憾,白天干兼職很累的,上家公司現在還沒發工資。。)
(1)先上爬取的資訊內容:
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class ChinadoctornetItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
# 爬取中國醫學人才網的條目(共5個條目)
# 醫院名稱
hospitalName = scrapy.Field()
# 醫院規模
hospitalSize = scrapy.Field ()
# 醫院所在地
hospitalAddress = scrapy.Field()
# 醫院科目
hospitalDesc = scrapy.Field()
# pass
(2)接著是spider裡面的內容
這裡用的是scrapy裡面的xpath路徑, 具體xpath自己可以用一個chrom helper來進行測試,
我提取的是整個醫院的item,//div[@class='newsjob']/ul/li
然後下面是提取item裡面的內容,在當前路徑下用 .
自己試著除錯著就能搞出來的
直接貼程式碼:
# encoding=utf8
import scrapy
from chinadoctornet.items import ChinadoctornetItem
class ChinaDocNet(scrapy.Spider):
# 啟動爬蟲的名稱
name = 'docNet'
# 爬取域名的範圍
allowed_domains = ['yixuezp.com']
# 爬蟲第一個url地址
start_urls = ['http://www.yixuezp.com/zhaopin?page={}'.format(n) for n in range(0, 464)] # 463
def parse(self, response):
# 醫院name
node_list = response.xpath("//div[@class='newsjob']/ul/li")
items = []
for node in node_list:
item = ChinadoctornetItem()
hospitalName = node.xpath("./a/text()").extract()
hospitalSize = node.xpath("./span[1]/text()").extract()
hospitalAddress = node.xpath("./span[2]/text()").extract()
hospitalDesc = node.xpath("./p/a/text()").extract()
item['hospitalName'] = hospitalName
item['hospitalSize'] = hospitalSize
item['hospitalAddress'] = hospitalAddress
item['hospitalDesc'] = hospitalDesc
items.append(item)
# return items # 如果直接return的話,一頁資料只會返回一條資料
yield item #用yield 的話,可以交給下載器,繼續執行下一步操作。
(3)以json格式進行下載資料
程式碼:
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
import json
class ChinadoctornetPipeline(object):
def process_item(self, item, spider):
return item
class JsonWriterPipeline(object):
def __init__(self):
self.file = open('中國醫學人才網招聘最新招聘專欄2.json', 'w', encoding='utf-8')
def process_item(self, item, spider):
line = json.dumps(dict(item), ensure_ascii=False) + "\n"
self.file.write(line)
return item
def spider_closed(self, spider):
self.file.close()
最後就是這樣子了, 下載器這一塊程式碼是直接複製上一份的,不過,程式碼都一樣,多記想想為什麼,就通了。
settings裡面的程式碼沒有動,只是吧ROBOTSTXT_OBEY設定為False了。
下次再進行幾個網站的爬取,早點找工作啊,還要找些典型的網站進行練手。