经过前面几篇的学习,像MonkeyLei:Python-爬虫基础-Xpath-爬取百度搜索列表(获取标题和真实url) MonkeyLei:Python-爬虫基础-Xpath-爬取百度风云榜旗下热点 等基本上xpath没啥问题了。。
然后就到了爬虫框架的使用,正好公司项目也是采用的这个,就自己先熟悉下。。这样即使看起公司的项目也会相对熟悉一些。。。
这个搞了一两天差不多了。。之前也是积累了很多知识,实践。。加上同事的快速指点,还是容易上手。。
这次看了几篇网友文章,直接上手的。。当然有官方的,可以考虑看官方的,一点点搞。印象更深。。我是想节约点时间...
https://www.jianshu.com/p/b2ca839afdb2
https://blog.csdn.net/houyanhua1/article/details/86545704
https://www.cnblogs.com/mlhz/p/10473517.html
这些文章或多或少都有有一些不全的地方,我们要自己汲取有用的流程,具体自己实践还是要重头开始搭建。。然后梳理爬虫框架Scrapy的执行流程。。。
https://scrapy.org/
后面流程跑通后,我又加了selenium的中间处理。。为了获取动态加载的页面..
基于之前的工程建个目录,然后利用所谓的脚手架来创建就好了。。上面链接有说明。还是那句话,按照自己的想法,用别人的知识构建自己的知识体系...
列几个改动的文件: - 环境不全的,先把需要的库都搞好再继续吧...
book.py
# -*- coding: utf-8 -*-
import scrapy
from ..items import ScraypyTestItem
from ..util.webdriver_util import Wedriver
class BookSpider(scrapy.Spider):
name = 'book'
# allowed_domains = ['douban.com']
start_urls = [] # 'http://douban.com/'
# 实例化浏览器对象 只能被调一次
def __init__(self, page_id=None):
# 爬取id为page_id的页面的内容
print('BookSpider __init__', page_id)
# TODO 通过page_id获取数据库的url信息,规则信息等等
self.b_jsload = True # 假设是动态页面需要webdriver加载
self.title_ruler = '//div[@class="pl2"]/a'
self.title_brief = '//div[@class="pl2"]/p/text()'
# 恶作剧,要被封ip的,我擦range(10000)
for i in range(1):
self.start_urls.append('https://movie.douban.com/chart')
# 动态加载的情况才需要引擎支持
if self.b_jsload:
# 初始化webdriver引擎,用于获取动态页面内容
self.browser = Wedriver.get_webdriver()
# 不能写在这 因为这里也会被调多次
def parse(self, response):
print(response)
# print(response.text)
# print(response.body)
# 然后利用xpath来解析我们需要的标题,简介等信息 xpath('string(.)')可以过滤掉内部标签,内容整合获取
titles = response.xpath(self.title_ruler).xpath('string(.)').extract()
briefs = response.xpath(self.title_brief).extract()
items = []
for index in range(len(titles)):
# print(titles[index].replace('\n', '').replace('\r', '').replace(' ', ''))
# print(briefs[index])
item = ScraypyTestItem()
item['title'] = titles[index].replace('\n', '').replace('\r', '').replace(' ', '')
item['director'] = briefs[index]
items.append(item)
return items
# 在整个爬虫结束之后才会被调用
def closed(self, spider):
print('BookSpider closed')
if self.b_jsload and self.browser:
self.browser.quit()
items.py - 定义实体类的bean哈。。左边就是字段名称,item就是靠这个字段取值
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class ScraypyTestItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
title = scrapy.Field()
director = scrapy.Field()
pipelines.py
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
class ScraypyTestPipeline(object):
# 开启爬虫时执行,只执行一次
def open_spider(self, spider):
# spider.hello = "world" # 为spider对象动态添加属性,可以在spider模块中获取该属性值
# 可以开启数据库等
print('open_spider')
# 处理提取的数据(保存数据)
def process_item(self, item, spider):
print('标题 ', item["title"])
print('简介 ', item["director"], '\n')
return item
# 关闭爬虫时执行,只执行一次 (如果爬虫中间发生异常导致崩溃,close_spider可能也不会执行)
def close_spider(self, spider):
# 可以关闭数据库等
print('close_spider')
webdriver_util.py
#!/usr/bin/python3
# -*- coding: utf-8 -*-
from selenium.webdriver.chrome.options import Options
from selenium import webdriver
'''
webdriver引擎创建管理
'''
class Wedriver:
@staticmethod
def get_webdriver():
return webdriver.Chrome(chrome_options=Wedriver.init_chrome_option())
@staticmethod
def init_chrome_option():
# 启动参数
chrome_option = Options()
prefs = {
'profile.default_content_setting_values': {
'images': 2, # 禁用图片的加载
# 'javascript': 2 # 禁用js,可能会导致通过js加载的互动数抓取失效
}
}
chrome_option.add_experimental_option("prefs", prefs)
chrome_option.add_argument('--headless') # 使用无头谷歌浏览器模式
chrome_option.add_argument('--disable-dev-shm-usage')
chrome_option.add_argument('--no-sandbox')
chrome_option.add_argument("window-size=1024,768")
chrome_option.add_argument('--disable-gpu')
chrome_option.add_argument('blink-settings=imagesEnabled=false')
# https://blog.csdn.net/dichun9655/article/details/93790652 - 返爬的方式
# chrome_option.add_experimental_option("debuggerAddress", "127.0.0.1:9222")
return chrome_option
middlewares.py
# -*- coding: utf-8 -*-
# Define here the models for your spider middleware
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/spider-middleware.html
from time import sleep
from scrapy import signals
# HtmlResponse是response对应的类
from scrapy.http import HtmlResponse
import selenium.webdriver.support.ui as ui
class ScraypyTestSpiderMiddleware(object):
# Not all methods need to be defined. If a method is not defined,
# scrapy acts as if the spider middleware does not modify the
# passed objects.
@classmethod
def from_crawler(cls, crawler):
# This method is used by Scrapy to create your spiders.
s = cls()
crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
return s
def process_spider_input(self, response, spider):
# Called for each response that goes through the spider
# middleware and into the spider.
# Should return None or raise an exception.
return None
def process_spider_output(self, response, result, spider):
# Called with the results returned from the Spider, after
# it has processed the response.
# Must return an iterable of Request, dict or Item objects.
for i in result:
yield i
def process_spider_exception(self, response, exception, spider):
# Called when a spider or process_spider_input() method
# (from other spider middleware) raises an exception.
# Should return either None or an iterable of Response, dict
# or Item objects.
pass
def process_start_requests(self, start_requests, spider):
# Called with the start requests of the spider, and works
# similarly to the process_spider_output() method, except
# that it doesn’t have a response associated.
# Must return only requests (not items).
for r in start_requests:
yield r
def spider_opened(self, spider):
spider.logger.info('Spider opened: %s' % spider.name)
class ScraypyTestDownloaderMiddleware(object):
# Not all methods need to be defined. If a method is not defined,
# scrapy acts as if the downloader middleware does not modify the
# passed objects.
@classmethod
def from_crawler(cls, crawler):
# This method is used by Scrapy to create your spiders.
s = cls()
crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
return s
def process_request(self, request, spider):
# Called for each request that goes through the downloader
# middleware.
# Must either:
# - return None: continue processing this request
# - or return a Response object
# - or return a Request object
# - or raise IgnoreRequest: process_exception() methods of
# installed downloader middleware will be called
return None
def process_response(self, request, response, spider):
# Called with the response returned from the downloader.
# Must either;
# - return a Response object
# - return a Request object
# - or raise IgnoreRequest
# return response
# 自行处理请求 - 采用动态加载的方式
if spider.b_jsload:
print('process_response: ', request.url)
bro = spider.browser
# 浏览器静默加载页面后等待10s(这个页面加载后后续还有很多js要执行,所以我们需要时间获取最终页面)
wait = ui.WebDriverWait(bro, 10)
bro.get(url=request.url)
# 如果等待页面加载完成,直接返回无需再等待;替换掉sleep的方式
wait.until(lambda driver: driver.page_source)
page_text = bro.page_source
return HtmlResponse(url=request.url, body=page_text, encoding='utf-8', request=request)
else:
return response
def process_exception(self, request, exception, spider):
# Called when a download handler or a process_request()
# (from other downloader middleware) raises an exception.
# Must either:
# - return None: continue processing this exception
# - return a Response object: stops process_exception() chain
# - return a Request object: stops process_exception() chain
pass
def spider_opened(self, spider):
spider.logger.info('Spider opened: %s' % spider.name)
settings.py - 该打开的功能要打开,不然有些脚本不带运行的哟
# -*- coding: utf-8 -*-
# Scrapy settings for scraypy_test project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
# https://doc.scrapy.org/en/latest/topics/settings.html
# https://doc.scrapy.org/en/latest/topics/downloader-middleware.html
# https://doc.scrapy.org/en/latest/topics/spider-middleware.html
BOT_NAME = 'scraypy_test'
SPIDER_MODULES = ['scraypy_test.spiders']
NEWSPIDER_MODULE = 'scraypy_test.spiders'
# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'scraypy_test (+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://doc.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',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36'
}
# Enable or disable spider middlewares
# See https://doc.scrapy.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
# 'scraypy_test.middlewares.ScraypyTestSpiderMiddleware': 543,
#}
# Enable or disable downloader middlewares
# See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html
DOWNLOADER_MIDDLEWARES = {
'scraypy_test.middlewares.ScraypyTestDownloaderMiddleware': 543,
}
# Enable or disable extensions
# See https://doc.scrapy.org/en/latest/topics/extensions.html
#EXTENSIONS = {
# 'scrapy.extensions.telnet.TelnetConsole': None,
#}
# Configure item pipelines
# See https://doc.scrapy.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {
'scraypy_test.pipelines.ScraypyTestPipeline': 300,
}
# Enable and configure the AutoThrottle extension (disabled by default)
# See https://doc.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://doc.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'
最后搞一个启动脚本 start.py
# -*- coding: utf-8 -*-
from scrapy import cmdline
# 爬取id为110的页面,爬虫则会根据110字段去数据库里面取对应的链接,规则之类的信息,然后进行爬取
cmdline.execute(('scrapy crawl book -a page_id=%d %s' % (110, '--nolog')).split())
规则xpath插件可以抓取,自己再改改就行。。
到此基本就搞定了。。可以跑了哟。。。
**工程地址: **https://gitee.com/heyclock/doc/tree/master/Python
标题和简介就是如下内容哈。。。
之前忘记截爬到的图了,现在被封ip了...