ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

Python自学- Scrapy爬虫(1)

2021-09-11 20:04:20  阅读:128  来源: 互联网

标签:rentHouses Python Scrapy 爬虫 scrapy html response div class


Python自学- Scrapy爬虫(1)

1、交互式命令模式——shell

Scrapy终端是一个交互终端,供您在未启动spider的情况下尝试及调试您的爬取代码。 其本意是用来测试提取数据的代码,不过您可以将其作为正常的Python终端,在上面测试任何的Python代码。

该终端是用来测试XPath或CSS表达式,查看他们的工作方式及从爬取的网页中提取的数据。 在编写您的spider时,该终端提供了交互性测试您的表达式代码的功能,免去了每次修改后运行spider的麻烦。

一旦熟悉了Scrapy终端后,您会发现其在开发和调试spider时发挥的巨大作用。

  • 使用下载器获取指定url的内容,同时进入命令行交互界面供用户进行调试
scrapy shell https://haimen.lianjia.com/ershoufang/rs/

image-20210906070559018

  • 打印response对象的状态码
response

image-20210906070630389

  • 在本机的浏览器打开给定的response。
view(response)

image-20210906064123389

  • 采用谷歌浏览器插件XPath Helper,定位到二手房的相关信息【标题和价格】。

image-20210906072513631

  • 提取出第一个房源的价格。
response.xpath("/html/body/div[@id='content']/div[@class='leftContent']/ul[@class='sellListContent']/li[@class='clear LOGVIEWDATA LOGCLICKDATA'][1]/div[@class='info clear']/div[@class='priceInfo']/div[@class='totalPrice totalPrice2']/span/text()").extract()

image-20210906072624815

  • 提取出本页所有房源的价格。
response.xpath("/html/body/div[@id='content']/div[@class='leftContent']/ul[@class='sellListContent']/li[@class='clear LOGVIEWDATA LOGCLICKDATA']/div[@class='info clear']/div[@class='priceInfo']/div[@class='totalPrice totalPrice2']/span/text()").extract()

image-20210906072900671

  • 提取出本页所有房源的标题
response.xpath("/html/body/div[@id='content']/div[@class='leftContent']/ul[@class='sellListContent']/li[@class='clear LOGVIEWDATA LOGCLICKDATA']/div[@class='info clear']/div[@class='title']/a/text()").extract()

image-20210906073019041

  • 打印出房源的个数

image-20210906073044475

2、Scrapy爬虫数据抓取

'''
Author: Gu Jiakai
Date: 2021-09-06 07:53:56
LastEditTime: 2021-09-06 08:04:29
LastEditors: Gu Jiakai
Description: 
FilePath: \rentHouses\rentHouses\spiders\lianjia.py
'''
import scrapy

class LianjiaSpider(scrapy.Spider):
    name='zufang'
    start_urls=['https://haimen.lianjia.com/ershoufang/rs/']

    def parse(self, response):
        print(response)
        title_list=response.xpath("/html/body/div[@id='content']/div[@class='leftContent']/ul[@class='sellListContent']/li[@class='clear LOGVIEWDATA LOGCLICKDATA']/div[@class='info clear']/div[@class='title']/a/text()").extract()
        price_list=response.xpath("/html/body/div[@id='content']/div[@class='leftContent']/ul[@class='sellListContent']/li[@class='clear LOGVIEWDATA LOGCLICKDATA']/div[@class='info clear']/div[@class='priceInfo']/div[@class='totalPrice totalPrice2']/span/text()").extract()
        for i,j in zip(title_list,price_list):
            print(i+':'+j+'万元')
  • 查看有多少个爬虫
scrapy list
  • 运行爬虫
scrapy crawl zufang

image-20210906080650313

3、Scrapy爬虫数据入库—

ipython是一个python的交互式shell。

ipython创建数据库及建表的相关语句。

# 调用sqlite3模块。
In [1]: import sqlite3
    
# sqlite3.connect()方法打开一个到 SQLite 数据库文件 database 的链接。
# 如果给定的数据库名称 filename 不存在,则该调用将创建一个数据库。
In [2]: zufang=sqlite3.connect('zufang.sqlite')

# 创建表格的SQL语句。
In [3]: create_table='create table zufang(title varchar(512),money varchar(128))'

# 该例程执行一个 SQL 语句。
In [4]: zufang.execute(create_table)
Out[4]: <sqlite3.Cursor at 0x2152bae1ab0>

# 退出命令行。
In [5]: exit

4、Scrapy爬虫数据入库二

lianjia.py

'''
Author: Gu Jiakai
Date: 2021-09-06 07:53:56
LastEditTime: 2021-09-06 08:50:29
LastEditors: Gu Jiakai
Description: 
FilePath: \rentHouses\rentHouses\spiders\lianjia.py
'''
import scrapy
from ..items import RenthousesItem

class LianjiaSpider(scrapy.Spider):
    name='zufang'
    start_urls=['https://haimen.lianjia.com/ershoufang/rs/']

    def parse(self, response):
        print(response)
        zf=RenthousesItem()
        title_list=response.xpath("/html/body/div[@id='content']/div[@class='leftContent']/ul[@class='sellListContent']/li[@class='clear LOGVIEWDATA LOGCLICKDATA']/div[@class='info clear']/div[@class='title']/a/text()").extract()
        price_list=response.xpath("/html/body/div[@id='content']/div[@class='leftContent']/ul[@class='sellListContent']/li[@class='clear LOGVIEWDATA LOGCLICKDATA']/div[@class='info clear']/div[@class='priceInfo']/div[@class='totalPrice totalPrice2']/span/text()").extract()
        for i,j in zip(title_list,price_list):
            zf['title']=i
            zf['money']=j
            yield zf
        #     print(i+':'+j+'万元')

items.py

'''
Author: Gu Jiakai
Date: 2021-09-06 07:51:37
LastEditTime: 2021-09-06 08:53:08
LastEditors: Gu Jiakai
Description: 
FilePath: \rentHouses\rentHouses\items.py
'''
# Define here the models for your scraped items
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/items.html

import scrapy

class RenthousesItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    title=scrapy.Field()
    money=scrapy.Field()
    pass

settings.py

'''
Author: Gu Jiakai
Date: 2021-09-06 07:51:37
LastEditTime: 2021-09-06 08:39:17
LastEditors: Gu Jiakai
Description: 
FilePath: \rentHouses\rentHouses\settings.py
'''
# Scrapy settings for rentHouses project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
#     https://docs.scrapy.org/en/latest/topics/settings.html
#     https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
#     https://docs.scrapy.org/en/latest/topics/spider-middleware.html

BOT_NAME = 'rentHouses'

SPIDER_MODULES = ['rentHouses.spiders']
NEWSPIDER_MODULE = 'rentHouses.spiders'


# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'rentHouses (+http://www.yourdomain.com)'

# Obey robots.txt rules
ROBOTSTXT_OBEY = True

# Configure maximum concurrent requests performed by Scrapy (default: 16)
#CONCURRENT_REQUESTS = 32

# Configure a delay for requests for the same website (default: 0)
# See https://docs.scrapy.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
#DOWNLOAD_DELAY = 3
# The download delay setting will honor only one of:
#CONCURRENT_REQUESTS_PER_DOMAIN = 16
#CONCURRENT_REQUESTS_PER_IP = 16

# Disable cookies (enabled by default)
#COOKIES_ENABLED = False

# Disable Telnet Console (enabled by default)
#TELNETCONSOLE_ENABLED = False

# Override the default request headers:
#DEFAULT_REQUEST_HEADERS = {
#   'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
#   'Accept-Language': 'en',
#}

# Enable or disable spider middlewares
# See https://docs.scrapy.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
#    'rentHouses.middlewares.RenthousesSpiderMiddleware': 543,
#}

# Enable or disable downloader middlewares
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
#    'rentHouses.middlewares.RenthousesDownloaderMiddleware': 543,
#}

# Enable or disable extensions
# See https://docs.scrapy.org/en/latest/topics/extensions.html
#EXTENSIONS = {
#    'scrapy.extensions.telnet.TelnetConsole': None,
#}

# Configure item pipelines
# See https://docs.scrapy.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {
   'rentHouses.pipelines.RenthousesPipeline': 300,
}

# Enable and configure the AutoThrottle extension (disabled by default)
# See https://docs.scrapy.org/en/latest/topics/autothrottle.html
#AUTOTHROTTLE_ENABLED = True
# The initial download delay
#AUTOTHROTTLE_START_DELAY = 5
# The maximum download delay to be set in case of high latencies
#AUTOTHROTTLE_MAX_DELAY = 60
# The average number of requests Scrapy should be sending in parallel to
# each remote server
#AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0
# Enable showing throttling stats for every response received:
#AUTOTHROTTLE_DEBUG = False

# Enable and configure HTTP caching (disabled by default)
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings
#HTTPCACHE_ENABLED = True
#HTTPCACHE_EXPIRATION_SECS = 0
#HTTPCACHE_DIR = 'httpcache'
#HTTPCACHE_IGNORE_HTTP_CODES = []
#HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'

pipelines.py

'''
Author: Gu Jiakai
Date: 2021-09-06 07:51:37
LastEditTime: 2021-09-06 08:58:00
LastEditors: Gu Jiakai
Description: 
FilePath: \rentHouses\rentHouses\pipelines.py
'''
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html


# useful for handling different item types with a single interface
from itemadapter import ItemAdapter
import sqlite3

class RenthousesPipeline:
    def open_spider(self,spider):
        self.con=sqlite3.connect('zufang.sqlite')
        self.cu=self.con.cursor()

    def process_item(self, item, spider):
        print(spider.name,'pipelines')
        insert_sql="insert into zufang values('{}','{}')".format(item['title'],item['money'])
        print(insert_sql)
        self.con.execute(insert_sql)
        self.con.commit()
        return item
    
    def spider_close(self,spider):
        self.con.close()
  • 执行爬虫
scrapy crawl zufang
  • 安装SQLite插件

image-20210906091757457

  • 新建查询

image-20210906091900908

  • 书写SQL语句,执行

image-20210906091939808

效果图:

image-20210906092001579

标签:rentHouses,Python,Scrapy,爬虫,scrapy,html,response,div,class
来源: https://www.cnblogs.com/gujiakai-top/p/15256586.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有