21天打造分散式爬蟲-房天下全國658城市房源(十一)

来源:https://www.cnblogs.com/derek1184405959/archive/2018/08/09/9446544.html
-Advertisement-
Play Games

項目:爬取房天下網站全國所有城市的新房和二手房信息 網站url分析 創建項目 sfw_spider.py items.py pipelines.py middleware.py 設置隨機User-Agent settings.py start.py ...


項目:爬取房天下網站全國所有城市的新房和二手房信息

網站url分析

1.獲取所有城市url

   http://www.fang.com/SoufunFamily.htm

    例如:http://cq.fang.com/

2.新房url

  http://newhouse.sh.fang.com/house/s/

3.二手房url

  http://esf.sh.fang.com/

4.北京新房和二手房url規則不同

   http://newhouse.fang.com/house/s/

   http://esf.fang.com/

創建項目

scrapy startproject fang

scrapy genspider sfw_spider "fang.com"

sfw_spider.py

# -*- coding: utf-8 -*-
import scrapy
import re
from fang.items import NewHouseItem,ESFHouseItem

class SfwSpiderSpider(scrapy.Spider):
    name = 'sfw_spider'
    allowed_domains = ['fang.com']
    start_urls = ['http://www.fang.com/SoufunFamily.htm']

    def parse(self, response):
        trs = response.xpath("//div[@class='outCont']//tr")
        provice = None
        for tr in trs:
            #排除掉第一個td,兩個第二個和第三個td標簽
            tds = tr.xpath(".//td[not(@class)]")
            provice_td = tds[0]
            provice_text = provice_td.xpath(".//text()").get()
            #如果第二個td裡面是空值,則使用上個td的省份的值
            provice_text = re.sub(r"\s","",provice_text)
            if provice_text:
                provice = provice_text
            #排除海外城市
            if provice == '其它':
                continue

            city_td = tds[1]
            city_links = city_td.xpath(".//a")
            for city_link in city_links:
                city = city_link.xpath(".//text()").get()
                city_url = city_link.xpath(".//@href").get()
                # print("省份:",provice)
                # print("城市:",city)
                # print("城市鏈接:",city_url)
                #下麵通過獲取的city_url拼接出新房和二手房的url鏈接
                #城市url:http://cq.fang.com/
                #新房url:http://newhouse.cq.fang.com/house/s/
                #二手房:http://esf.cq.fang.com/
                url_module = city_url.split("//")
                scheme = url_module[0]     #http:
                domain = url_module[1]     #cq.fang.com/
                if 'bj' in domain:
                    newhouse_url = ' http://newhouse.fang.com/house/s/'
                    esf_url = ' http://esf.fang.com/'
                else:
                    #新房url
                    newhouse_url = scheme + '//' + "newhouse." + domain + "house/s/"
                    #二手房url
                    esf_url = scheme + '//' + "esf." + domain + "house/s/"
                # print("新房鏈接:",newhouse_url)
                # print("二手房鏈接:",esf_url)

                #meta裡面可以攜帶一些參數信息放到Request裡面,在callback函數裡面通過response獲取
                yield scrapy.Request(url=newhouse_url,
                                     callback=self.parse_newhouse,
                                     meta = {'info':(provice,city)}
                                     )

                yield scrapy.Request(url=esf_url,
                                     callback=self.parse_esf,
                                     meta={'info': (provice, city)})


    def parse_newhouse(self,response):
        #新房
        provice,city = response.meta.get('info')
        lis = response.xpath("//div[contains(@class,'nl_con')]/ul/li")
        for li in lis:
            name = li.xpath(".//div[contains(@class,'house_value')]//div[@class='nlcd_name']/a/text()").get()
            if name:
                name = re.sub(r"\s","",name)
                #居室
                house_type_list = li.xpath(".//div[contains(@class,'house_type')]/a/text()").getall()
                house_type_list = list(map(lambda x:re.sub(r"\s","",x),house_type_list))
                rooms = list(filter(lambda x:x.endswith(""),house_type_list))
                #面積
                area = "".join(li.xpath(".//div[contains(@class,'house_type')]/text()").getall())
                area = re.sub(r"\s|-|/","",area)
                #地址
                address = li.xpath(".//div[@class='address']/a/@title").get()
                address = re.sub(r"[請選擇]","",address)
                sale = li.xpath(".//div[contains(@class,'fangyuan')]/span/text()").get()
                price = "".join(li.xpath(".//div[@class='nhouse_price']//text()").getall())
                price = re.sub(r"\s|廣告","",price)
                #詳情頁url
                origin_url = li.xpath(".//div[@class='nlcd_name']/a/@href").get()

                item = NewHouseItem(
                    name=name,
                    rooms=rooms,
                    area=area,
                    address=address,
                    sale=sale,
                    price=price,
                    origin_url=origin_url,
                    provice=provice,
                    city=city
                )
                yield item

        #下一頁
        next_url = response.xpath("//div[@class='page']//a[@class='next']/@href").get()
        if next_url:
            yield scrapy.Request(url=response.urljoin(next_url),
                                 callback=self.parse_newhouse,
                                 meta={'info': (provice, city)}
                                 )


    def parse_esf(self,response):
        #二手房
        provice, city = response.meta.get('info')
        dls = response.xpath("//div[@class='shop_list shop_list_4']/dl")
        for dl in dls:
            item = ESFHouseItem(provice=provice,city=city)
            name = dl.xpath(".//span[@class='tit_shop']/text()").get()
            if name:
                infos = dl.xpath(".//p[@class='tel_shop']/text()").getall()
                infos = list(map(lambda x:re.sub(r"\s","",x),infos))
                for info in infos:
                    if "" in info:
                        item["rooms"] = info
                    elif '' in info:
                        item["floor"] = info
                    elif '' in info:
                        item['toward'] = info
                    elif '' in info:
                        item['area'] = info
                    elif '年建' in info:
                        item['year'] = re.sub("年建","",info)
                item['address'] = dl.xpath(".//p[@class='add_shop']/span/text()").get()
                #總價
                item['price'] = "".join(dl.xpath(".//span[@class='red']//text()").getall())
                #單價
                item['unit'] = dl.xpath(".//dd[@class='price_right']/span[2]/text()").get()
                item['name'] = name
                detail = dl.xpath(".//h4[@class='clearfix']/a/@href").get()
                item['origin_url'] = response.urljoin(detail)
                yield item
        #下一頁
        next_url = response.xpath("//div[@class='page_al']/p/a/@href").get()
        if next_url:
            yield scrapy.Request(url=response.urljoin(next_url),
                                 callback=self.parse_esf,
                                 meta={'info': (provice, city)}
                                 )

items.py

# -*- coding: utf-8 -*-

import scrapy

class NewHouseItem(scrapy.Item):
    #省份
    provice = scrapy.Field()
    # 城市
    city = scrapy.Field()
    # 小區
    name = scrapy.Field()
    # 價格
    price = scrapy.Field()
    # 幾居,是個列表
    rooms = scrapy.Field()
    # 面積
    area = scrapy.Field()
    # 地址
    address = scrapy.Field()
    # 是否在售
    sale = scrapy.Field()
    # 房天下詳情頁面的url
    origin_url = scrapy.Field()

class ESFHouseItem(scrapy.Item):
    # 省份
    provice = scrapy.Field()
    # 城市
    city = scrapy.Field()
    # 小區名字
    name = scrapy.Field()
    # 幾室幾廳
    rooms = scrapy.Field()
    #
    floor = scrapy.Field()
    # 朝向
    toward = scrapy.Field()
    # 年代
    year = scrapy.Field()
    # 地址
    address = scrapy.Field()
    # 建築面積
    area = scrapy.Field()
    # 總價
    price = scrapy.Field()
    # 單價
    unit = scrapy.Field()
    # 詳情頁url
    origin_url = scrapy.Field()

pipelines.py

# -*- coding: utf-8 -*-

from scrapy.exporters import JsonLinesItemExporter

class FangPipeline(object):
    def __init__(self):
        self.newhouse_fp = open('newhouse.json','wb')
        self.esfhouse_fp = open('esfhouse.json','wb')
        self.newhouse_exporter = JsonLinesItemExporter(self.newhouse_fp,ensure_ascii=False)
        self.esfhouse_exporter = JsonLinesItemExporter(self.esfhouse_fp,ensure_ascii=False)

    def process_item(self, item, spider):
        self.newhouse_exporter.export_item(item)
        self.esfhouse_exporter.export_item(item)
        return item

    def close_spider(self,spider):
        self.newhouse_fp.close()
        self.esfhouse_fp.close()

middleware.py 設置隨機User-Agent

# -*- coding: utf-8 -*-

import random

class UserAgentDownloadMiddleware(object):
    USER_AGENTS = [
        'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36',
        'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0 ',
        'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36',
        'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.71 Safari/537.1 LBBROWSER',
    ]

    def process_request(self,request,spider):
        user_agent = random.choice(self.USER_AGENTS)
        request.headers['User-Agent'] = user_agent

settings.py

ROBOTSTXT_OBEY = False

DOWNLOAD_DELAY = 1

DOWNLOADER_MIDDLEWARES = {
   'fang.middlewares.UserAgentDownloadMiddleware': 543,
}

ITEM_PIPELINES = {
   'fang.pipelines.FangPipeline': 300,
}

start.py

from scrapy import cmdline

cmdline.execute("scrapy crawl sfw_spider".split())

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 原文轉自: https://www.cnblogs.com/Survivalist/p/8012266.html 隨筆:最近再做這些年的知識整理,今天整理到了架構這方便,就索性拿出來和大家分享一下,有什麼寫錯的,歡迎大家指正 架構拆分的演變: 1.傳統項目的架構:特點: 1.all in one(所 ...
  • 一、struts2簡介 1、Struts2是一個基於MVC設計模式的Web應用框架 只要是web層框架 一般就會遵守MVC設計模式 2、struts2與struts1的關係? 沒關係 WebWork基於xwork 3、struts2是一個可插拔式框架(解耦) 通過filter與javaweb結合的 ...
  • 機器配置為:VS2013+opencv2.4.13+Win-64bit。 分割線 本節將利用ROI將一幅圖像疊加到另一幅圖像的指定位置。具體過程見下麵代碼 分割線 代碼演示 分割線 顯示結果 分割線 程式說明我們會看到程式里有這麼一行代碼 1 signal.copyTo(imageROI, mask ...
  • 函數 函數在 中稱為方法,在其他語言中可能稱為函數,函數,方法就是定義在類中具有特定功能的程式。函數,在 中可稱為方法。 函數的格式: 關鍵字是用來結束該函數,即方法的,並將後面的具體結果返回給調用者即可,如果函數的返回值為 ,則表示沒有返回值。 如何快速寫你所需要的函數? 明確返回值類型,和參數列 ...
  • 位運算符(二進位位運算) | 運算符 | 運算 | 例子 | | |: :| :| | 3 2 2 =12| | | 右移 | 3 1 = 1 3/2=1 | | | 無符號右移 | 3 1 = 1 3/2=1 | | & | 與運算 | 6 & 3 = 2| | \| | 或運算 | 6 \| 3 ...
  • random模塊用於生成各種隨機數,常用的方法有: random.random():產生0-1之間的隨機小數。 random.randint(a, b):產生a-b之間的隨機數,包含a和b。 random.randrange(a, b):產生a-b之間的隨機數,包含a,不包含b。 random.ch ...
  • 報數序列是指一個整數序列,按照其中的整數的順序進行報數,得到下一個數。其前五項如下: 1. 1 2. 11 3. 21 4. 1211 5. 111221 1 被讀作 "one 1" ("一個一") , 即 11。 11 被讀作 "two 1s" ("兩個一"), 即 21。 21 被讀作 "one ...
  • 續playPoker類 運行截圖 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...