今天勺子接到了領導交給我的一個任務:網上收集江蘇省內醫院的名錄,信息越詳細越好,於是,不糾結、不抱怨,抄起scrapy一路開爬!
一、網站選擇
網上醫院信息網站還是很多的,經過對比篩選,勺子最終選擇了99醫院庫(https://yyk.99.com.cn/)。這個網站的醫院信息內容非常全面,一些不知名的醫院都能查得到,完全滿足領導要求。
二、網站分析
進入網址:https://yyk.99.com.cn/jiangsu/,就可以看到江蘇全省的醫院名錄了(居然有將近4000家),點擊每個醫院名稱,即可進入醫院的詳情頁,在詳情頁的醫院介紹模塊裡,可以查到醫院的性質、地址、等級等信息,因此,整體思路就比較清晰了,先獲取近4000家醫院的全部鏈接,再逐一訪問獲取每家醫院的詳細信息。
三、創建工程
開始動手,兩行代碼創建工程:
<code>scrapy startproject jiangsuhospital
scrapy genspider hospital '99.com.cn'/<code>
工程創建完成後,再setting.py裡進行必要配置,將ROBOTSTXT_OBEY置為False,設置請求頭,打開pipelines等。
四、核心代碼
hospital.py的代碼如下:
<code>import scrapy
from jiangsuhospital.items import JiangsuhospitalItem
class HospitalSpider(scrapy.Spider):
name = 'hospital'
allowed_domains = ['99.com.cn']
start_urls = ['https://yyk.99.com.cn/jiangsu/']
def parse(self, response):
divs = response.xpath("//html/body//div[@class='m-table-2']//tr")
#拼接各家醫院的url
for div in divs:
trs = div.xpath('.//td')
for tr in trs:
href = tr.xpath('.//a/@href').extract_first()
next_url = 'https://yyk.99.com.cn'+href+'jianjie.html'
#請求所有醫院的url
yield scrapy.Request(next_url,callback=self.parse_detail)/<code>
五、數據保存
通過pipelines.py將數據保存至csv文件中,csv數據保存基本可以寫成以下固定格式:
<code>import os
import csv
class JiangsuhospitalPipeline(object):
def open_spider(self,spider):
store_file = os.path.dirname(__file__) + '\\\\result\\\\result.csv'
self.file = open(store_file,'w',newline='')
self.writer = csv.writer(self.file)
def process_item(self, item, spider):
if item['mingcheng'] :
self.writer.writerow((item['mingcheng'],item['bieming'],item['shuxing'],item['dianhua'],item['dizhi'],item['chengshi'],item['yuanzhang'],item['jianyuan'],item['leixing'],item['dengji'],item['keshi'],item['renshu'],item['bingchuang'],item['nianmenzhen'],item['yibao']))
return item
def close_spider(self,spider):
self.file.close()/<code>
六、結果展示
<code>scrapy crawl hospital,表格就出來了,調整就是這樣/<code>
很簡單的一個小工程,很好的解決了領導的需求,在此源碼奉上,供大家參考,下載地址:https://github.com/cxxc2001/jiangsuhospital。
對代碼有問題,或需要數據,或其他商業合作,可以私信勺子!
【一把勺子,挖掘數據律動!!】
閱讀更多 一把勺子 的文章