用python寫一個簡單的爬蟲儲存在json檔案中
學習python沒多久,所以只能寫一個很簡單的爬蟲啦~~
我使用annacada 自帶的spyder來寫爬蟲的,這次我們要爬取得網站是http://www.drugbank.ca/drugs,
主要是爬取裡面每種藥物的資訊到json檔案中,包括有
DrugBank ID, Name , Weight, Structure, Categories, TherapeuticIndication。
首先我們先要在命令提示符那裡輸入一個語句來建立專案:scrapy startproject drugs //drugs是自己取得名字。
然後命令提示符上就會有關於建立的資料夾在哪個路徑,我們對應去找就會找到的。找到之後我們會看到很多的檔案,其中我們先用spyder去開啟items.py
import scrapy
class TutorialItem(scrapy.Item):
#define the fields for your item here like:
#name = scrapy.Field()
DrugBankId = scrapy.Field(); //這些名字(DrugBankId,Name......)都是我們想要爬取出來的資訊。
Name = scrapy.Field();
Weight = scrapy.Field();
Structure = scrapy.Field();
Categories = scrapy.Field();
TherapeuticIndication = scrapy.Field();
Pass
然後我們在spider資料夾下自己建立一個.py結尾的檔案來編寫主要的程式碼。
我建立了drugbank.py的檔案,然後在裡面輸入:
#-*- coding:utf-8 -*-
import scrapy
import string
from drugs.items import TutorialItem
class drugbank(scrapy.Spider):
# 定義爬蟲的名稱,主要main方法使用
name = 'drugbank' //在命令提示符中用來呼叫的。
allowed_domains=["drugbank.ca"]
start_urls=["http://www.drugbank.ca/drugs"]
# 解析資料
def parse(self, response):
items = []
i="0"
for sel in response.xpath('//table/tbody/tr'):
item = TutorialItem()
a=string.atoi(i)+1
i=str(a)
item['DrugBankId']=sel.xpath('//table/tbody/tr['+i+']/td[1]/a/text()').extract()
item['Name']=sel.xpath('//table/tbody/tr['+i+']/td[2]/strong/a/text()').extract()
item['Weight']=sel.xpath('//table/tbody/tr['+i+']/td[3]/text()[1]').extract()
item['Structure']=sel.xpath('//table/tbody/tr['+i+']/td[4]/a/img/@src').extract()
item['Categories']=sel.xpath('//table/tbody/tr['+i+']/td[5]/a/text()').extract()
item['TherapeuticIndication']=sel.xpath('//table/tbody/tr['+i+']/td[6]/text()').extract()
items.append(item)
yield item
#翻頁
next_page =response.xpath('//ul/li[@class="next_page"]/a/@href')
if next_page:
url = response.urljoin(next_page[0].extract())
#爬每一頁
yield scrapy.Request(url, self.parse)
我們在命令提示符中進入到drugs目錄下,即輸入cd drugs,然後回車再輸入 scrapy crawl drugbank -o items.json -t json其中drugbank是在drugbank檔案中的name的屬性,items.json是你想將資料存放到這個檔案中,所以這個名字是自定義的。
執行完這個,我們就可以在drugs資料夾下找到items.json檔案,裡面就存放著從網頁下爬取出來的藥物的資訊。