爬虫入门基础-Scrapy框架的Spalsh渲染要点
我们可以把互联网比作一张大网,而爬虫(即网络爬虫)便是在网上爬行的蜘蛛。把网的节点比作一个个网页,爬虫爬到这就相当于访问了该页面,获取了其信息。可以把节点间的连线比作网页与网页之间的链接关系,这样蜘蛛通过一个节点后,可以顺着节点连线继续爬行到达下一个节点,即通过一个网页继续获取后续的网页,这样整个网的节点便可以被蜘蛛全部爬行到,网站的数据就可以被抓取下来了。
爬虫概述
简单来说,爬虫就是获取网页并提取和保存信息的自动化程序,下面概要介绍一下。
(1) 获取网页爬虫首先要做的工作就是获取网页,这里就是获取网页的源代码。源代码里包含了网页的部分有用信息,所以只要把源代码获取下来,就可以从中提取想要的信息了。
前面讲了请求和响应的概念,向网站的服务器发送一个请求,返回的响应体便是网页源代码。所以,最关键的部分就是构造一个请求并发送给服务器,然后接收到响应并将其解析出来,那么这个流程怎样实现呢?总不能手工去截取网页源码吧?
不用担心,Python提供了许多库来帮助我们实现这个操作,如urllib、requests等。我们可以用这些库来帮助我们实现HTTP请求操作,请求和响应都可以用类库提供的数据结构来表示,得到响应之后只需要解析数据结构中的Body部分即可,即得到网页的源代码,这样我们可以用程序来实现获取网页的过程了。
(2) 提取信息获取网页源代码后,接下来就是分析网页源代码,从中提取我们想要的数据。首先,最通用的方法便是采用正则表达式提取,这是一个万能的方法,但是在构造正则表达式时比较复杂且容易出错。
另外,由于网页的结构有一定的规则,所以还有一些根据网页节点属性、CSS选择器或XPath来提取网页信息的库,如Beautiful Soup、pyquery、lxml等。使用这些库,我们可以高效快速地从中提取网页信息,如节点的属性、文本值等。
提取信息是爬虫非常重要的部分,它可以使杂乱的数据变得条理清晰,以便我们后续处理和分析数据。
(3) 保存数据提取信息后,我们一般会将提取到的数据保存到某处以便后续使用。这里保存形式有多种多样,如可以简单保存为TXT文本或JSON文本,也可以保存到数据库,如MySQL和MongoDB等,也可保存至远程服务器,如借助SFTP进行操作等。
(4) 自动化程序说到自动化程序,意思是说爬虫可以代替人来完成这些操作。首先,我们手工当然可以提取这些信息,但是当量特别大或者想快速获取大量数据的话,肯定还是要借助程序。爬虫就是代替我们来完成这份爬取工作的自动化程序,它可以在抓取过程中进行各种异常处理、错误重试等操作,确保爬取持续高效地运行。
能抓怎样的数据?
在网页中我们能看到各种各样的信息,最常见的便是常规网页,它们对应着HTML代码,而最常抓取的便是HTML源代码。
另外,可能有些网页返回的不是HTML代码,而是一个JSON字符串(其中API接口大多采用这样的形式),这种格式的数据方便传输和解析,它们同样可以抓取,而且数据提取更加方便。
此外,我们还可以看到各种二进制数据,如图片、视频和音频等。利用爬虫,我们可以将这些二进制数据抓取下来,然后保存成对应的文件名。
另外,还可以看到各种扩展名的文件,如CSS、JavaScript和配置文件等,这些其实也是最普通的文件,只要在浏览器里面可以访问到,就可以将其抓取下来。
上述内容其实都对应各自的URL,是基于HTTP或HTTPS协议的,只要是这种数据,爬虫都可以抓取。
Scrapy框架之Spalsh渲染
原理说明:
基于spalsh渲染后HTML,通过配置文件解析,入库。 提高了效率,一天可以写几十个配置dict,即完成几十个网站爬虫的编写。
配置文件说明:{ industry_type : 政策 , # 行业类别 website_type : 央行 , # 网站/微信公众号名称 url_type : 中国人民银行-条法司-规范性文件 , # 网站模块 link : http://www.pbc.gov.cn/tiaofasi/144941/3581332/index.html , # 访问链接 article_rows_xpath : //div[@id= r_con ]//table//tr/td/font[contains(@class, newslist_style )] , # 提取文章列表xpath对象 title_xpath : ./a , # 提取标题 title_parse : ./@title , # 提取标题 title_link_xpath : ./a/@href , # 提取标题链接 date_re_switch : False , # 是否使用正则提取日期时间 date_re_expression : , # 日期时间正则表达式 date_xpath : ./following-sibling::span[1] , # 提取日期时间 date_parse : ./text() , # 提取日期时间 content : //*[@ >
完整代码参考
# -*- coding: utf-8 -*- 需求列表:使用任何资讯网站的抓取 http://www.pbc.gov.cn/tiaofasi/144941/3581332/index.html http://www.pbc.gov.cn/tiaofasi/144941/144959/index.html https://www.mps.gov.cn/n2254314/n2254487/ https://www.mps.gov.cn/n2253534/n2253535/index.html http://www.qth.gov.cn/xxsbxt/sxdw/gajxx/ from risk_control_info.items import BIgFinanceNews import dateparser from w3lib.url import canonicalize_url from urllib.parse import urljoin import scrapy from scrapy_splash import SplashRequest from risk_control_info.utils import make_md5, generate_text, clean_string import re script = function main(splash, args) splash.images_enabled = false splash:set_user_agent( {ua} ) assert(splash:go(args.url)) assert(splash:wait(args.wait)) return splash:html() end .format( ua= Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.157 Safari/537.36 ) class BigFinanceAllGovSpider(scrapy.Spider): name = big_finance_all_gov custom_settings = { RANDOMIZE_DOWNLOAD_DELAY: True, DOWNLOAD_DELAY: 60 / 360.0, CONCURRENT_REQUESTS_PER_IP: 8, DOWNLOADER_MIDDLEWARES: { scrapy_splash.SplashCookiesMiddleware: 723, scrapy_splash.SplashMiddleware: 725, scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware: 810, # risk_control_info.middlewares.SplashProxyMiddleware: 843, # 代理ip,此方法没成功 risk_control_info.middlewares.RandomUserAgentMiddleware: 843, risk_control_info.middlewares.SeleniumMiddleware: 844 # 入库 ITEM_PIPELINES: { risk_control_info.pipelines.RiskControlInfoPipeline: 401, risk_control_info.pipelines.MysqlPipeline: 402, SPIDER_MIDDLEWARES: { risk_control_info.middlewares.RiskControlInfoSpiderMiddleware: 543, scrapy_splash.SplashDeduplicateArgsMiddleware: 100, def __init__(self, **kwargs): super().__init__() self.env = kwargs.get(env, online) def start_requests(self): for target in self.target_info(): if target.get(title_xpath) and target.get(title_link_xpath) / and target.get(date_xpath) and target.get(article_rows_xpath): self.logger.info(f 目标网站可配置爬虫信息:{target} ) # 使用selenium if target.get( config ) and eval(eval(target.get( config )).get(use_selenium)): self.logger.info(f 使用 Selenium 请求 {target[link]} ) yield scrapy.Request(url=target[link], meta={ target : target, use_selenium : True callback=self.parse, else: # 默认使用 Splash self.logger.info(f 使用 Splash 请求 {target[link]} ) yield SplashRequest(url=target[link], meta={ target : target}, callback=self.parse, # endpoint=execute, # args={ # lua_source: script, # wait: 8}, endpoint=render.json, args={ # lua_source: script, # proxy: f http://{proxy_ip_dict[ip]}:{proxy_ip_dict[port]} , wait: 10, html: 1, png: 1 def parse(self, response): target = response.meta[target] article_rows = response.xpath(target[article_rows_xpath]) # 遍历所有文字列表 for article_row in article_rows: item = BIgFinanceNews() # 处理标题 _article_row = article_row.xpath(target[title_xpath]) # 定位标题 item[title] = clean_string( generate_text(_article_row.xpath(target[title_parse]).extract_first().strip())) # 解析标题 # 处理链接 if target.get(prefix): item[title_link] = urljoin(target[prefix], article_row.xpath( target[title_link_xpath]).extract_first()) else: item[title_link] = article_row.xpath(target[title_link_xpath]).extract_first() # 处理发布日期 # 日期顺序规则 date_order = YMD _title_time = article_row.xpath(target[date_xpath]) # 定位:发布时间 _date_str = clean_string( generate_text(_title_time.xpath(target[date_parse]).extract_first())) # 解析:发布时间 if not eval(target.get(date_re_switch)): item[title_time] = dateparser.parse(_date_str, settings={DATE_ORDER: date_order}).strftime( %Y-%m-%d ) else: # 使用正则提取时间字符串,存在默认正则表达式 date_re_expression = target.get(date_re_expression, None) _expression = date_re_expression or r (20/d{2}[-/]?/d{2}[-/]?/d{2}) results = re.findall(r %s % _expression, _date_str, re.S) self.logger.info(f _date_str:{_date_str},results:{results} ) if results: item[title_time] = dateparser.parse(results[0], settings={DATE_ORDER: date_order}).strftime( %Y-%m-%d ) else: item[title_time] = None # 以下写死的 item[bi_channel] = gov item[industry_type] = f {target[industry_type]} item[website_type] = f {target[website_type]} item[url_type] = f {target[url_type]} item[title_hour] = 0 # 原网站没有发布时间,0代替 item[source_type] = 0 # 数据来源,0 网站web, 1 微信公众号 item[redis_duplicate_key] = make_md5(item[title] + canonicalize_url(item[title_link])) # 请求详情页 # 使用selenium if target.get( config ) and eval(eval(target.get( config )).get(use_selenium)): self.logger.info(f 使用 Selenium 请求 {item[title_link]} ) yield scrapy.Request(url=item[title_link], meta={ target : target, use_selenium : True, item : item callback=self.parse_detail, else: # 使用 Splash self.logger.info(f 使用 Splash 请求 {item[title_link]} ) yield SplashRequest(url=item[title_link], meta={ target : target, item : item callback=self.parse_detail, # endpoint=execute, # args={ # lua_source: script, # wait: 8}, endpoint=render.json, args={ # lua_source: script, # proxy: f http://{proxy_ip_dict[ip]}:{proxy_ip_dict[port]} , wait: 20, html: 1, png: 1 def parse_detail(self, response): self.logger.info(f 处理详情页 {response.url} ) item = response.meta[item] target = response.meta[target] print(response.xpath(target[content])) if response.xpath(target[content]): item[content] = generate_text(response.xpath(target[content]).extract_first()) else: item[content] = yield item @staticmethod def target_info(): 返回目标网站信息 target_list = [ industry_type : 政策 , # 行业类别 website_type : 央行 , # 网站/微信公众号名称 url_type : 中国人民银行-条法司-规范性文件 , # 网站模块 link : http://www.pbc.gov.cn/tiaofasi/144941/3581332/index.html , # 访问链接 article_rows_xpath : //div[@id= r_con ]//table//tr/td/font[contains(@class, newslist_style )], # 提取文章列表xpath对象 title_xpath : ./a , # 提取标题 title_parse : ./@title , # 提取标题 title_link_xpath : ./a/@href , # 提取标题链接 date_re_switch : False , # 是否使用正则提取日期时间 date_re_expression : , # 日期时间正则表达式 date_xpath : ./following-sibling::span[1] , # 提取日期时间 date_parse : ./text() , # 提取日期时间 content : //*[@ , # 正文HTML xpath prefix : http://www.pbc.gov.cn/ , # link前缀 config : {use_selenium:False} # 其他配置:是否使用selenium(默认使用spalsh) industry_type : 政策 , # 行业类别 website_type : 央行 , # 网站/微信公众号名称 url_type : 中国人民银行-条法司-其他文件 , # 网站模块 link : http://www.pbc.gov.cn/tiaofasi/144941/144959/index.html , # 访问链接 article_rows_xpath : //div[@id= r_con ]//table//tr/td/font[contains(@class, newslist_style )], title_xpath : ./a , title_parse : ./@title , title_link_xpath : ./a/@href , date_re_switch : False , # 是否使用正则提取日期时间 date_re_expression : , # 日期时间正则表达式 date_xpath : ./following-sibling::span[1] , date_parse : ./text() , content : //*[@ , # 正文HTML xpath prefix : http://www.pbc.gov.cn/ , config : {use_selenium:False} industry_type : 政策 , # 行业类别 website_type : 公安部 , # 网站/微信公众号名称 url_type : 中华人民共和国公安部-规划计划 , # 网站模块 link : https://www.mps.gov.cn/n2254314/n2254487/ , # 访问链接 article_rows_xpath : //span/dl/dd, title_xpath : ./a , title_parse : ./text() , title_link_xpath : ./a/@href , date_re_switch : True , # 是否使用正则提取日期时间 ( 2020-04-14 ) date_re_expression : , # 日期时间正则表达式 date_xpath : ./span , date_parse : ./text() , content : //*[@ , # 正文HTML xpath prefix : https://www.mps.gov.cn/ , config : {use_selenium:True} industry_type : 政策 , # 行业类别 website_type : 公安部 , # 网站/微信公众号名称 url_type : 中华人民共和国公安部-公安要闻 , # 网站模块 link : https://www.mps.gov.cn/n2253534/n2253535/index.html , # 访问链接 article_rows_xpath : //span/dl/dd, title_xpath : ./a , title_parse : ./text() , title_link_xpath : ./a/@href , date_re_switch : True , # 是否使用正则提取日期时间 ( 2020-04-14 ) date_re_expression : , # 日期时间正则表达式 date_xpath : ./span , date_parse : ./text() , content : //*[@ , # 正文HTML xpath prefix : https://www.mps.gov.cn/ , config : {use_selenium:True} industry_type : 政策 , # 行业类别 website_type : 公安部 , # 网站/微信公众号名称 url_type : 七台河市人民政府-信息上报系统-市辖单位-公安局 , # 网站模块 link : http://www.qth.gov.cn/xxsbxt/sxdw/gajxx/ , # 访问链接 article_rows_xpath : //td[contains(text(), 公安局 )]/parent::tr/parent::tbody/parent::table/parent::td/parent::tr/following::tr[1]/td/table//tr/td/a/parent::td/parent::tr, title_xpath : ./td/a , title_parse : ./@title , title_link_xpath : ./td/a/@href , date_re_switch : False , # 是否使用正则提取日期时间 ( 2020-04-14 ) date_re_expression : , # 日期时间正则表达式 date_xpath : ./td[3] , date_parse : ./text() , content : //*[@ , # 正文HTML xpath prefix : http://www.qth.gov.cn/xxsbxt/sxdw/gajxx/ , config : {use_selenium:False} for target in target_list: yield target6、爬虫代理
以上是关于Scrapy框架之Spalsh渲染信息,以上信息只能适合基本采集,如果需要详细长期采集需要配合使用爬虫代。例如使用亿牛云爬虫代理加强版配上以上demo更能方便长期稳定采集出想要的数据信息。
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/53611.html
javamysqlpythonRedis相关文章
- 双11当晚写的天猫爬虫,爬虫神器 scrapy 大法好!!!
- Python - 手把手教你用Scrapy编写一个爬虫
- 学习爬虫之Scrapy框架学习(六)–1.直接使用scrapy;使用scrapy管道;使用scrapy的媒体管道类进行猫咪图片存储。媒体管道类学习。自建媒体管道类存储图片
- 网络爬虫——scrapy案例「建议收藏」
- python3+Scrapy爬虫实战(一)—— 初识Scrapy
- Python: “股票数据定向爬虫”实例
- Python: “股票数据Scrapy爬虫”实例
- Python爬虫——爬取王者荣耀全英雄台词语音
- spider-flow流程图爬虫,一个高度灵活可配置的爬虫平台!
- python爬虫scrapy框架_nodejs爬虫框架
- Scrapy爬虫入门
- 微博爬虫 | 微博评论爬取下载,同步获取一二级评论
- Scrapy 爬虫框架[通俗易懂]
- 【2023 最新】微博爬虫及配套数据分析可视化教程
- java爬虫问题二: 使用jsoup爬取数据class选择器中空格多选择怎么解决
- 爬虫介绍
- Python爬虫之scrapy框架学习
- Python爬虫案例--音乐网站mp3文件的提取
- Python + PyQt5 实现美剧爬虫可视工具详解编程语言
- 简单制作Scrapy爬虫
- python、java爬虫使用代理的区别
- 高效爬虫神器:Scrapy结合Redis的优势(scrapyredis)
- 爬虫为何借助Redis追求更高效率(爬虫为什么使用redis)