Scrapy是: 由Python语言开发的一个快速、高层次的屏幕抓取和web抓取框架,用于抓取web站点并从页面中提取结构化的数据。
Scrapy用途广泛,可以用于数据挖掘、监测和自动化测试
Scrapy指令:
创建项目:scrapy startproject xxx(工程名)
进入项目:cd xxx #进入某个文件夹下
创建爬虫:scrapy genspider xxx(爬虫名) xxx.com (爬取域)
运行爬虫:scrapy crawl XXX(爬虫名)
列出所有爬虫:scrapy list
生成文件:scrapy crawl xxx -o xxx.json (生成某种类型的文件)
爬虫文件:
(1)spiders文件夹:存放爬虫文件的文件夹。
(2)items.py:定义需要抓取的数据。
(3)pipelines.py:负责数据抓取以后的处理工作。
(4)settings.py:爬虫的各种配置信息。
dmoz.py
import scrapy
class DmozSpider(scrapy.Spider): # 继承Spider类
name = "dmoz" # 爬虫的唯一标识,不能重复,启动爬虫的时候要用
allowed_domains = ["dmoz.org"] # 限定域名,只爬取该域名下的网页
start_urls = [ # 开始爬取的链接
"https://www.baidu.com/"
]
def parse(self, response):
title=response.xpath('//title/text()').extract()
tit=response.xpath('//title/text()').re('\w')
print(tit)
创建main.py才可以在pycharm中运行
main.py
from scrapy import cmdline
cmdline.execute("scrapy crawl example".split())
setting.py改掉君子协议
# Obey robots.txt rules
ROBOTSTXT_OBEY = False
在dmoz.py文件中存储数据:通过item
from (工程名).items import (items.py中的class名字)
item =(items.py中的class名字)
item['phone'] = person_info[3]
yield item
例子:
from baidu.items import PersonInfoItem
item = PersonInfoItem()
person_info = person.xpath('td/text()').extract()
item['name'] = person_info[0]
item['age'] = person_info[1]
item['salary'] = person_info[2]
item['phone'] = person_info[3]
yield item
在items.py中:
class 名字(scrapy.Item):
name = scrapy.Field()
往数据库中存储数据:
setting.py加入
MONGODB_HOST = '127.0.0.1'
MONGODB_PORT = 27017
MONGODB_DBNAME = 'blogspider'
MONGODB_DOCNAME = 'blog'
pipelines.py
import pymongo
from scrapy.utils.project import get_project_settings
settings = get_project_settings()
class TutorialPipeline:
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):
person_info = dict(item)
self.post.insert(person_info)
return item
例程:
test.py
# -*- coding: utf-8 -*-
import scrapy
from test_scrapy.items import TestScrapyItem
class TestSpider(scrapy.Spider):
name = 'test'
allowed_domains = ['exercise.kingname.info']
start_urls = ['http://exercise.kingname.info/exercise_xpath_3.html']
def parse(self, response):
person_list = response.xpath('//div[@class="person_table"]/table/tbody/tr')
for person in person_list:
item = TestScrapyItem()
person_info = person.xpath('td/text()').extract()
item['name'] = person_info[0]
item['age'] = person_info[1]
item['salary'] = person_info[2]
item['phone'] = person_info[3]
print(person_info)
yield item
items.py
import scrapy
class TestScrapyItem(scrapy.Item):
name = scrapy.Field()
age = scrapy.Field()
salary = scrapy.Field()
phone = scrapy.Field()
main.py
from scrapy import cmdline
cmdline.execute("scrapy crawl test".split())
pipelines.py
import pymongo
from scrapy.utils.project import get_project_settings
settings = get_project_settings()
class TestScrapyPipeline:
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):
person_info = dict(item)
self.post.insert(person_info)
return item
setting.py
# -*- coding: utf-8 -*-
# Scrapy settings for test_scrapy 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 = 'test_scrapy'
SPIDER_MODULES = ['test_scrapy.spiders']
NEWSPIDER_MODULE = 'test_scrapy.spiders'
# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'test_scrapy (+http://www.yourdomain.com)'
# Obey robots.txt rules
ROBOTSTXT_OBEY = False
# 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,image/webp,image/apng,*/*;q=0.8',
'accept-encoding': 'gzip, deflate, br',
'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8',
'cache-control': 'max-age=0',
'dnt': '1',
'upgrade-insecure-requests': '1',
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'
}
# Enable or disable spider middlewares
# See https://docs.scrapy.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
# 'test_scrapy.middlewares.TestScrapySpiderMiddleware': 543,
#}
# Enable or disable downloader middlewares
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
# 'test_scrapy.middlewares.TestScrapyDownloaderMiddleware': 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 = {
'test_scrapy.pipelines.TestScrapyPipeline': 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'
MONGODB_HOST = '127.0.0.1'
MONGODB_PORT = 27017
MONGODB_DBNAME = 'blogspider'
MONGODB_DOCNAME = 'blog'
引入请求头
在setting.py中:
DEFAULT_REQUEST_HEADERS = {}
欢迎关注