??從圖上可以看到每一條出租房屋信息单默,主要包括:價(jià)格碘举,戶型,面積搁廓,樓層引颈,裝修耕皮,類型,所在區(qū)蝙场,小區(qū)明场,出租方式,朝向李丰,鄰近的地鐵線苦锨。
??開始上代碼:
??創(chuàng)建一個(gè)scrapy項(xiàng)目(scrapy startproject Anjuke_Spider)。會(huì)生成如下圖3的目錄嗜憔。然后秃励,在“spiders”文件夾下創(chuàng)建一個(gè)py文檔,這里命名為“anjuke_zufang”吉捶。然后加入“run”文件夺鲜。最后的目錄如圖4.
??下面,跳過(guò)scrapy的"settings"設(shè)置呐舔,直接寫主要代碼币励。
??引入所要用的庫(kù):
import scrapy
from scrapy.spiders import Rule
from scrapy.linkextractors import LinkExtractor
from Anjuke_Spider.items import AnjukeSpiderItem
??然后創(chuàng)建一個(gè)爬蟲的類:
class AnjukeSpider(scrapy.spiders.CrawlSpider): name = 'anjuke'
??寫起始的url:
start_urls = ['https://bj.zu.anjuke.com/']
??接下來(lái)就是本文的核心,LinkExtractor珊拼,首先得根據(jù)抓包數(shù)據(jù)和網(wǎng)頁(yè)進(jìn)行分析食呻,并不是所有的網(wǎng)頁(yè)爬取都能使用LinkExtractor。首先得分析需要爬取的網(wǎng)頁(yè)url澎现。
首先分析不同的目錄頁(yè)url仅胞,點(diǎn)擊頁(yè)面下的頁(yè)碼項(xiàng),去不同目錄頁(yè)剑辫,發(fā)現(xiàn)其url如下:
https://bj.zu.anjuke.com/?from=navigation 第1頁(yè)
https://bj.zu.anjuke.com/fangyuan/p2/ 第2頁(yè)
https://bj.zu.anjuke.com/fangyuan/p3/ 第3頁(yè)
https://bj.zu.anjuke.com/fangyuan/p4/ 第4頁(yè)
https://bj.zu.anjuke.com/fangyuan/p5/ 第5頁(yè)
??其中試著將第1頁(yè)的url改為“https://bj.zu.anjuke.com/fangyuan/p1/”干旧,訪問(wèn)這個(gè)url,發(fā)現(xiàn)返回的正是第1頁(yè)的頁(yè)面妹蔽。 這樣便發(fā)現(xiàn)房源的目錄頁(yè)面有這樣的規(guī)律椎眯,他們url大致一樣,改變的僅是最后的頁(yè)碼編號(hào)讹开,這可以用如下的代碼匹配房源目錄頁(yè)面的url:
https://bj.zu.anjuke.com/fangyuan/p\d+/
??在得到房源目錄頁(yè)面后盅视,點(diǎn)擊房源進(jìn)入房源頁(yè)面,獲取所要的信息旦万,如圖5闹击,我們點(diǎn)擊網(wǎng)頁(yè)獲取我們需要的信息,可以發(fā)現(xiàn)其網(wǎng)址類似于圖6所示成艘,形如:
https://bj.zu.anjuke.com/fangyuan/1203399585?from=Filter_1&hfilter=filterlist
https://bj.zu.anjuke.com/fangyuan/1202089286?from=Filter_2&hfilter=filterlist
https://bj.zu.anjuke.com/fangyuan/1200258936?from=Filter_3&hfilter=filterlist
??可以發(fā)現(xiàn)不同的網(wǎng)頁(yè)赏半,在url上主要是url末尾的10位數(shù)字不同贺归。url的?號(hào)后的內(nèi)容一般是jquery断箫,有些內(nèi)容可以去掉這樣來(lái)簡(jiǎn)化url拂酣。把問(wèn)號(hào)后的內(nèi)容去掉發(fā)現(xiàn)其仍能夠訪問(wèn)房源的頁(yè)面,這樣便能找到房源頁(yè)面的url的規(guī)律仲义,可以用如下的代碼匹配房源的url:
https://bj.zu.anjuke.com/fangyuan/\d{10}
接下開始使用“Rule”和“LinkExtractor”:
rules = (
Rule(LinkExtractor(allow='fangyuan/p\d+/'), follow=True),
Rule(LinkExtractor(allow='https://bj.zu.anjuke.com/fangyuan/\d{10}'), callback='parse_item'),
)
??第一行“Rule(LinkExtractor(allow='fangyuan/p\d+/'), follow=True)”婶熬,用“allow”指定要訪問(wèn)的網(wǎng)址,因?yàn)榍懊嬉呀?jīng)指定start_urls埃撵,所以這里將“follow”指定為“True”赵颅,表示在start_urls后面添加,合起來(lái)即“https://bj.zu.anjuke.com/fangyuan/p\d+/”暂刘,這里訪問(wèn)的是房源的目錄頁(yè)饺谬。
第二行“Rule(LinkExtractor(allow='https://bj.zu.anjuke.com/fangyuan/\d{10}'), callback='parse_item')”是在第一行訪問(wèn)房源頁(yè)的基礎(chǔ)上,訪問(wèn)每一個(gè)房源頁(yè)谣拣,“callback”指定下面對(duì)數(shù)據(jù)進(jìn)行處理的方法募寨。
??接下來(lái)就該定義一個(gè)方法,方法名應(yīng)該與“callback”指定的方法名相同森缠。
def parse_item(self, response):
price = int(response.xpath("http://ul[@class='house-info-zufang cf']/li[1]/span[1]/em/text()").extract_first())
house_type = response.xpath("http://ul[@class='house-info-zufang cf']/li[2]/span[2]/text()").extract_first()
area = int(response.xpath("http://ul[@class='house-info-zufang cf']/li[3]/span[2]/text()").extract_first().replace('平方米',''))
rent_type = response.xpath("http://ul[@class='title-label cf']/li[1]/text()").extract_first()
towards = response.xpath("http://ul[@class='house-info-zufang cf']/li[4]/span[2]/text()").extract_first()
floor = response.xpath("http://ul[@class='house-info-zufang cf']/li[5]/span[2]/text()").extract_first()
decoration = response.xpath("http://ul[@class='house-info-zufang cf']/li[6]/span[2]/text()").extract_first()
building_type = response.xpath("http://ul[@class='house-info-zufang cf']/li[7]/span[2]/text()").extract_first()
district = response.xpath("http://ul[@class='house-info-zufang cf']/li[8]/a[2]/text()").extract_first()
station = response.xpath("http://ul[@class='house-info-zufang cf']/li[8]/a[3]/text()").extract_first()
community = response.xpath("http://ul[@class='house-info-zufang cf']/li[8]/a[1]/text()").extract_first()
subway_line = response.xpath("http://ul[@class='title-label cf']/li[3]/text()").extract_first()
??方法parse_item的response返回的便是房源頁(yè)面的HTML數(shù)據(jù)拔鹰,因?yàn)闆]有json數(shù)據(jù),所以只能從HTML數(shù)據(jù)匹配所需要的數(shù)據(jù)辅鲸。這里用的Xpath格郁,獲取price(租金)、house_type(戶型)独悴、area(面積)、rent_type(出租方式)锣尉、towards(朝向)刻炒、floor(樓層)、decoration(裝修)自沧、building_type(樓類型)坟奥、district(所在區(qū))、station(臨近地鐵站)拇厢、community(社區(qū)爱谁、小區(qū))、subway_line(地鐵線路)孝偎。
最后貼上anjuke_zufang.py的完整代碼:
import scrapy
from scrapy.spiders import Rule
from scrapy.linkextractors import LinkExtractor
from Anjuke_Spider.items import AnjukeSpiderItem
class AnjukeSpider(scrapy.spiders.CrawlSpider):
name = 'anjuke'
start_urls = ['https://bj.zu.anjuke.com/']
rules = (
Rule(LinkExtractor(allow='fangyuan/p\d+/'), follow=True),
Rule(LinkExtractor(allow='https://bj.zu.anjuke.com/fangyuan/\d{10}'), callback='parse_item'),
)
def parse_item(self, response):
price = int(response.xpath("http://ul[@class='house-info-zufang cf']/li[1]/span[1]/em/text()").extract_first())
house_type = response.xpath("http://ul[@class='house-info-zufang cf']/li[2]/span[2]/text()").extract_first()
area = int(response.xpath("http://ul[@class='house-info-zufang cf']/li[3]/span[2]/text()").extract_first().replace('平方米',''))
rent_type = response.xpath("http://ul[@class='title-label cf']/li[1]/text()").extract_first()
towards = response.xpath("http://ul[@class='house-info-zufang cf']/li[4]/span[2]/text()").extract_first()
floor = response.xpath("http://ul[@class='house-info-zufang cf']/li[5]/span[2]/text()").extract_first()
decoration = response.xpath("http://ul[@class='house-info-zufang cf']/li[6]/span[2]/text()").extract_first()
building_type = response.xpath("http://ul[@class='house-info-zufang cf']/li[7]/span[2]/text()").extract_first()
district = response.xpath("http://ul[@class='house-info-zufang cf']/li[8]/a[2]/text()").extract_first()
station = response.xpath("http://ul[@class='house-info-zufang cf']/li[8]/a[3]/text()").extract_first()
community = response.xpath("http://ul[@class='house-info-zufang cf']/li[8]/a[1]/text()").extract_first()
subway_line = response.xpath("http://ul[@class='title-label cf']/li[3]/text()").extract_first()
item = AnjukeSpiderItem()
item['price'] = price
item['house_type'] = house_type
item['area'] = area
item['rent_type'] = rent_type
item['towards'] = towards
item['floor'] = floor
item['decoration'] = decoration
item['building_type'] = building_type
item['district'] = district
item['station'] = station
item['community'] = community
item['subway_line'] = subway_line
yield item
??對(duì)于scrapy項(xiàng)目访敌,除了要寫爬蟲的主程序,還需要配置settings衣盾,items寺旺,pipelines爷抓,middleware等文件。還需要修改run文件阻塑。對(duì)于items文件修改如下:
import scrapy
class AnjukeSpiderItem(scrapy.Item):
price = scrapy.Field()
house_type = scrapy.Field()
area = scrapy.Field()
rent_type = scrapy.Field()
towards = scrapy.Field()
floor = scrapy.Field()
decoration = scrapy.Field()
building_type = scrapy.Field()
district = scrapy.Field()
community = scrapy.Field()
station = scrapy.Field()
subway_line = scrapy.Field()
本項(xiàng)目需要在settings中設(shè)置headers蓝撇,如下:
DEFAULT_REQUEST_HEADERS = {
'Connection': 'keep-alive',
'Upgrade-Insecure-Requests': '1',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.75 Safari/537.36',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
'Accept-Encoding': 'gzip, deflate, br',
'Accept-Language': 'zh-CN,zh;q=0.9'
}
??run文件如下:
from scrapy.crawler import CrawlerProcess
from scrapy.utils.project import get_project_settings
# 獲取settings.py模塊的設(shè)置
from Anjuke_Spider.spiders.anjuke_zufang import AnjukeSpider
settings = get_project_settings()
process = CrawlerProcess(settings=settings)
# 可以添加多個(gè)spider
process.crawl(AnjukeSpider)
# 啟動(dòng)爬蟲,會(huì)阻塞陈莽,直到爬取完成
process.start()
??其次還需要在pipelines中將結(jié)果寫入一個(gè)文件中渤昌,本項(xiàng)目將結(jié)果寫入了mysql數(shù)據(jù)庫(kù),這里不再詳細(xì)介紹走搁。
??其中要注意的是独柑,在爬取的過(guò)程中,會(huì)觸發(fā)網(wǎng)站的反爬機(jī)制朱盐,但是在設(shè)置一個(gè)隨機(jī)的時(shí)間間隔便能繼續(xù)進(jìn)行群嗤,在settings中設(shè)置:
DOWNLOAD_DELAY = 1.5