這篇文章主要介紹創建一個簡單的spider,順便介紹一下對網頁元素的選取方式(css selector, xpath selector)。
第一步:創建spider工程
打開命令行運行以下命令:
scrapy startproject homelink_selling_index
創建出的工程結構如下:
│ scrapy.cfg
│
└─lianjia_shub
│ items.py
│ pipelines.py
│ settings.py
│ __init__.py
│
└─spiders
__init__.py
第二步:定義spider(homelink_selling_index)
需要抓取的頁面元素如下圖:
導入命名空間:
import scrapy
定義spider:
class homelink_selling_index_spider(scrapy.Spider): # 定義spider的名字,在調用spider進行crawling的時候會用到: # scrapy crawl <spider.name> name = "homelink_selling_index" # 如果沒有特別指定其他的url,spider會以start_urls中的鏈接為入口開始爬取 start_urls = ["http://bj.lianjia.com/ershoufang/pg1tt2/"] # parse是scrapy.Spider處理http response的默認入口 # parse會對start_urls里的所有鏈接挨個進行處理 def parse(self, response): # 獲取當前頁面的房屋列表 #house_lis = response.css('.house-lst .info-panel') house_lis = response.xpath('//ul[@class="house-lst"]/li/div[@class="info-panel"]') # 把結果輸出到文件(在命令行中房屋標題會因為編碼原因顯示為亂碼) with open("homelink.log", "wb") as f: ## 使用css selector進行操作 #average_price = response.css('.secondcon.fl li:nth-child(1)').css('.botline a::text').extract_first() #f.write("Average Price: " + str(average_price) + "\r\n") #yesterday_count = response.css('.secondcon.fl li:last-child').css('.botline strong::text').extract_first() #f.write("Yesterday Count: " + str(yesterday_count) + "\r\n") #for house_li in house_lis: # link = house_li.css('a::attr("href")').extract_first() # 獲取房屋的鏈接地址 # title = house_li.css('a::text').extract_first() # 獲取房屋的標題 # price = house_li.css('.price .num::text').extract_first() # 獲取房屋的價格 # 使用xpath selector進行操作 average_price = response.xpath('//div[@class="secondcon fl"]//li[1]/span[@class="botline"]//a/text()').extract_first() f.write("Average Price: " + str(average_price) + "\r\n") yesterday_count = response.xpath('//div[@class="secondcon fl"]//li[last()]//span[@class="botline"]/strong/text()').extract_first() f.write("Yesterday Count: " + str(yesterday_count) + "\r\n") for house_li in house_lis: link = house_li.xpath('.//a/@href').extract_first() # 注意這里xpath的語法,前面要加上".",否則會從文檔根節點而不是當前節點為起點開始查詢 title = house_li.xpath('.//a/text()').extract_first() price = house_li.xpath('.//div[@class="price"]/span[@class="num"]/text()').extract_first() f.write("Title: {0}\tPrice:{1}\r\n\tLink: {2}\r\n".format(title.encode('utf-8'), price, link))
第三步:查看結果
Average Price: 44341 Yesterday Count: 33216 Title: 萬科假日風景全明格局 南北精裝三居 滿五唯一 Price:660 Link: http://bj.lianjia.com/ershoufang/xxx.html Title: 南北通透精裝三居 免稅帶車位 前后對花園 有鑰匙 Price:910 Link: http://bj.lianjia.com/ershoufang/xxx.html Title: 西直門 時代之光名苑 西南四居 滿五唯一 誠心出售 Price:1200 Link: http://bj.lianjia.com/ershoufang/xxx.html
......
結語:
通過上面的三步,我們可以對網頁元素進行簡單的爬取操作了。但是這里還沒有真正利用好Scrapy提供給我們的很多方便、強大的功能,比如: ItemLoader, Pipeline等。這些操作會在后續的文章中繼續介紹。