Python自学- Scrapy爬虫(1)
1、交互式命令模式——shell
Scrapy终端是一个交互终端,供您在未启动spider的情况下尝试及调试您的爬取代码。 其本意是用来测试提取数据的代码,不过您可以将其作为正常的Python终端,在上面测试任何的Python代码。
该终端是用来测试XPath或CSS表达式,查看他们的工作方式及从爬取的网页中提取的数据。 在编写您的spider时,该终端提供了交互性测试您的表达式代码的功能,免去了每次修改后运行spider的麻烦。
一旦熟悉了Scrapy终端后,您会发现其在开发和调试spider时发挥的巨大作用。
- 使用下载器获取指定url的内容,同时进入命令行交互界面供用户进行调试
scrapy shell https://haimen.lianjia.com/ershoufang/rs/
- 打印response对象的状态码
response
- 在本机的浏览器打开给定的response。
view(response)
- 采用谷歌浏览器插件XPath Helper,定位到二手房的相关信息【标题和价格】。
- 提取出第一个房源的价格。
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()
- 提取出本页所有房源的价格。
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()
- 提取出本页所有房源的标题
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()
- 打印出房源的个数
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
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插件
- 新建查询
- 书写SQL语句,执行
效果图: