地址:https://jn.zu.ke.com/zufang
1,首先確定要爬取的數據
2,查看數據來源
數據直接在網頁中展示,不是動態加載,也不需要cookie,更沒有什么反爬(之所以寫這篇文章是因為我對scrapy框架不了解,正在學習中,加深一下印象)
3.找下一頁的數據,尋找url規律
可以看到地址https://jn.zu.ke.com/zufang/pg2/ https://jn.zu.ke.com/zufang/pg3/.。。。。。是有一定規律的
#url可以這樣表示
start_urls = [f'https://jn.zu.ke.com/zufang/pg{i}/#contentList' for i in range(1,101)]
4,數據來源分析好了之后就要開始創建項目了
不知道scrapy怎么用的同學可以看我的另外幾篇文章 scrapy基本命令 scrapy框架持久化存儲 scrapy分布式爬蟲 增量式爬蟲
5,開始編寫代碼
1,settings.py配置文件需要改一些配置
2,item.py確定需要的數據
import scrapy class PropertiesItem(scrapy.Item): # define the fields for your item here like: # name = scrapy.Field() title = scrapy.Field() link = scrapy.Field() address = scrapy.Field() big = scrapy.Field() where = scrapy.Field() how = scrapy.Field() price = scrapy.Field() name = scrapy.Field()
3,進行編寫爬蟲文件
import copy import scrapy from properties.items import PropertiesItem class ExampleSpider(scrapy.Spider): name = 'example' allowed_domains = ['example.com'] start_urls = [f'https://jn.zu.ke.com/zufang/pg{i}/#contentList' for i in range(1,101)] def parse(self, response): node_list = response.xpath('//div[@class="content__list--item--main"]') item = PropertiesItem() for node in node_list: item["title"] = node.xpath("./p[1]/a/text()").extract_first().strip() item["link"] = response.urljoin(node.xpath("./p[1]/a/@href").extract_first().strip()) item["address"] = node.xpath("./p[2]/a[3]/text()").extract_first().strip() item["big"] = node.xpath("./p[2]/text()[5]").extract_first().strip() item["where"] = node.xpath("./p[2]/text()[6]").extract_first().strip() item["how"] = node.xpath("./p[2]/text()[7]").extract_first().strip() item["price"] = node.xpath( './span[@class="content__list--item-price"]/em/text()').extract_first().strip() + '元/月' # item["name"] ='none' # yield item yield scrapy.Request( url=item["link"], callback=self.makes, meta={"item": copy.deepcopy(item)}, dont_filter=True ) def makes(self,response): item = response.meta['item'] item["name"] = response.xpath('//span[@class="contact_name"]/@title').extract_first() yield item
4,編寫管道文件pipelines.py
import csv class PropertiesPipeline: def __init__(self): self.fp=None def open_spider(self,spider): print('=====爬蟲開始=====') self.fp = open('貝殼.csv', 'w', newline='', encoding="utf8") self.csv_writer=csv.writer(self.fp) self.csv_writer.writerow(["標題", "鏈接", '地址', "大小", "方向", "居室", "價格","姓名"]) def process_item(self, item, spider): self.csv_writer.writerow( [item["title"], item["link"], item["address"], item["big"], item["where"], item["how"], item["price"],item['name']] ) return item def close_spider(self,spider): self.fp.close() print('=====爬蟲結束=====')
別的文件就不需要做任何更改了,想要保存到數據庫 ,csv等地方可以看我的博客 scrapy持久化存儲 python操作csv,Excel,word
這就是我爬取好的數據,爬取下來是有很多重復數據的,是因為這個網站的原因,他在展示數據的時候就是從一個大列表里面抽取數據來展示,你每刷新一次頁面數據也就不一樣,可以用數據分析相關模塊進行去重,后續會在博客中更新,我目前是存儲在csv中,wps,office自帶去重功能