程序笔记   发布时间:2022-07-11  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了Python自学- Scrapy爬虫(1)大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

Python自学- Scrapy爬虫(1)

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

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

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

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

Python自学- Scrapy爬虫(1)

  • 打印response对象的状态码
response
@H_262_4@

Python自学- Scrapy爬虫(1)

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

Python自学- Scrapy爬虫(1)

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

Python自学- Scrapy爬虫(1)

  • 提取出第一个房源的价格。
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='@R_376_10586@lPrice @R_376_10586@lPrice2']/span/text()").extract()
@H_262_4@

Python自学- Scrapy爬虫(1)

  • 提取出本页所有房源的价格。
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='@R_376_10586@lPrice @R_376_10586@lPrice2']/span/text()").extract()
@H_262_4@

Python自学- Scrapy爬虫(1)

  • 提取出本页所有房源的标题
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()
@H_262_4@

Python自学- Scrapy爬虫(1)

  • 打印出房源的个数
@H_262_4@

Python自学- Scrapy爬虫(1)

2、Scrapy爬虫数据抓取@H_944_3@
'''
Author: Gu JiaKai
Date: 2021-09-06 07:53:56
LastEditTime: 2021-09-06 08:04:29
LastEditors: Gu JiaKai
Description: 
FilePath: rentHousesrentHousesspiderslianjia.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='@R_376_10586@lPrice @R_376_10586@lPrice2']/span/text()").extract()
        for i,j in zip(title_list,price_list):
            print(i+':'+j+'万元')
  • 查看有多少个爬虫
scrapy list
  • 运行爬虫
scrapy crawl zufang
@H_262_4@

Python自学- Scrapy爬虫(1)

3、Scrapy爬虫数据入库—@H_944_3@ @H_262_4@ipython是一个python的交互式sHell。

@H_262_4@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爬虫数据入库二@H_944_3@ @H_262_4@lianjia.py

'''
Author: Gu JiaKai
Date: 2021-09-06 07:53:56
LastEditTime: 2021-09-06 08:50:29
LastEditors: Gu JiaKai
Description: 
FilePath: rentHousesrentHousesspiderslianjia.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='@R_376_10586@lPrice @R_376_10586@lPrice2']/span/text()").extract()
        for i,j in zip(title_list,price_list):
            zf['title']=i
            zf['money']=j
            yield zf
        #     print(i+':'+j+'万元')
@H_262_4@items.py

'''
Author: Gu JiaKai
Date: 2021-09-06 07:51:37
LastEditTime: 2021-09-06 08:53:08
LastEditors: Gu JiaKai
Description: 
FilePath: rentHousesrentHousesitems.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
@H_262_4@setTings.py

'''
Author: Gu JiaKai
Date: 2021-09-06 07:51:37
LastEditTime: 2021-09-06 08:39:17
LastEditors: Gu JiaKai
Description: 
FilePath: rentHousesrentHousessetTings.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'
@H_262_4@pipelines.py

'''
Author: Gu JiaKai
Date: 2021-09-06 07:51:37
LastEditTime: 2021-09-06 08:58:00
LastEditors: Gu JiaKai
Description: 
FilePath: rentHousesrentHousespipelines.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
@H_262_4@

Python自学- Scrapy爬虫(1)

  • 新建查询
@H_262_4@

Python自学- Scrapy爬虫(1)

@H_262_4@

Python自学- Scrapy爬虫(1)

@H_262_4@效果图:

@H_262_4@

Python自学- Scrapy爬虫(1)

大佬总结

以上是大佬教程为你收集整理的Python自学- Scrapy爬虫(1)全部内容,希望文章能够帮你解决Python自学- Scrapy爬虫(1)所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。