最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python Scrapy框架第一個(gè)入門程序示例

 更新時(shí)間:2020年02月05日 12:23:28   作者:hankleo  
這篇文章主要介紹了Python Scrapy框架第一個(gè)入門程序,結(jié)合實(shí)例形式分析了Python Scrapy框架項(xiàng)目的搭建、抓取字段設(shè)置、數(shù)據(jù)庫保存等相關(guān)操作技巧,需要的朋友可以參考下

本文實(shí)例講述了python Scrapy框架第一個(gè)入門程序。分享給大家供大家參考,具體如下:

首先創(chuàng)建項(xiàng)目:

scrappy start project maitian

第二步: 明確要抓取的字段items.py

import scrapy
class MaitianItem(scrapy.Item):
  # define the fields for your item here like:
  # name = scrapy.Field()
  title = scrapy.Field()
  price = scrapy.Field()
  area = scrapy.Field()
  district = scrapy.Field()

第三步: 在spider目錄下創(chuàng)建爬蟲文件: zufang_spider.py

2.1 創(chuàng)建一個(gè)類,并繼承scrapy的一個(gè)子類: scrapy.Spider

2.2 自定義爬取名, name="" 后面運(yùn)行框架需要用到;

2.3 定義爬取目標(biāo)網(wǎng)址

2.4 定義scrapy的方法

下面是簡單項(xiàng)目:

import scrapy
from maitian.items import MaitianItem
class MaitianSpider(scrapy.Spider):
  name = "zufang"
  start_urls = ['http://bj.maitian.cn/zfall/PG1']
  def parse(self, response):
    for zufang_itme in response.xpath('//div[@class="list_title"]'):
      yield {
        'title': zufang_itme.xpath('./h1/a/text()').extract_first().strip(),
        'price': zufang_itme.xpath('./div[@class="the_price"]/ol/strong/span/text()').extract_first().strip(),
        'area': zufang_itme.xpath('./p/span/text()').extract_first().replace('㎡', '').strip(),
        'district': zufang_itme.xpath('./p//text()').re(r'昌平|朝陽|東城|大興|豐臺|海淀|石景山|順義|通州|西城')[0],
      }
    next_page_url = response.xpath(
      '//div[@id="paging"]/a[@class="down_page"]/@href').extract_first()
    if next_page_url is not None:
      yield scrapy.Request(response.urljoin(next_page_url))

第四步: 在settings.py文件中設(shè)置數(shù)據(jù)保存到數(shù)據(jù)庫

.
.
.
ITEM_PIPELINES = {'maitian.pipelines.MaitianPipeline': 300,}
MONGODB_HOST = '127.0.0.1'
MONGODB_PORT = 27017
MONGODB_DBNAME = 'maitian'
MONGODB_DOCNAME = 'zufang'

第五步: 通過管道pipelines.py 連接上面的操作

import pymongo
from scrapy.conf import settings
class MaitianPipeline(object):
  def __init__(self):
    host = settings['MONGODB_HOST']
    port = settings['MONGODB_PORT']
    db_name = settings['MONGODB_DBNAME']
    client = pymongo.MongoClient(host=host, port=port)
    db = client[db_name]
    self.post = db[settings['MONGODB_DOCNAME']]
  def process_item(self, item, spider):
    zufang = dict(item)
    self.post.insert(zufang)
    return item

其中 middlewares.py 文件暫不處理

以上簡單的scrapy爬蟲項(xiàng)目搭建完畢了

更多相關(guān)內(nèi)容可查看本站專題:《Python Socket編程技巧總結(jié)》、《Python正則表達(dá)式用法總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總

希望本文所述對大家基于Scrapy框架的Python程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評論

永登县| 上蔡县| 新巴尔虎右旗| 德庆县| 江华| 两当县| 武汉市| 博白县| 安泽县| 察雅县| 龙井市| 阿瓦提县| 醴陵市| 离岛区| 远安县| 新竹市| 视频| 东辽县| 黄石市| 平乐县| 哈巴河县| 正宁县| 尚义县| 凤阳县| 美姑县| 锦州市| 安吉县| 田阳县| 新晃| 湘潭市| 江源县| 陇南市| 揭阳市| 思茅市| 盐边县| 简阳市| 筠连县| 南郑县| 安西县| 文成县| 葫芦岛市|