前言
Scrapy是一个非常好的抓取框架,它不仅提供了一些开箱可用的基础组建,还能够根据自己的需求,进行强大的自定义。本文主要给大家介绍了关于Python抓取框架Scrapy之页面提取的相关内容,分享出来供大家参考学习,下面随着小编来一起学习学习吧。
在开始之前,关于scrapy框架的入门大家可以参考这篇文章://www.jb51.net/article/87820.htm
下面创建一个爬虫项目,以图虫网为例抓取图片。
一、内容分析
打开 图虫网,顶部菜单“发现” “标签”里面是对各种图片的分类,点击一个标签,比如“美女”,网页的链接为:https://tuchong.com/tags/美女/,我们以此作为爬虫入口,分析一下该页面:
打开页面后出现一个个的图集,点击图集可全屏浏览图片,向下滚动页面会出现更多的图集,没有页码翻页的设置。Chrome右键“检查元素”打开开发者工具,检查页面源码,内容部分如下:
<div class="content"> <div class="widget-gallery"> <ul class="pagelist-wrapper"> <li class="gallery-item...
可以判断每一个li.gallery-item是一个图集的入口,存放在ul.pagelist-wrapper下,div.widget-gallery是一个容器,如果使用 xpath 选取应该是://div[@class="widget-gallery"]/ul/li,按照一般页面的逻辑,在li.gallery-item下面找到对应的链接地址,再往下深入一层页面抓取图片。
但是如果用类似 Postman 的HTTP调试工具请求该页面,得到的内容是:
<div class="content"> <div class="widget-gallery"></div></div>
也就是并没有实际的图集内容,因此可以断定页面使用了Ajax请求,只有在浏览器载入页面时才会请求图集内容并加入div.widget-gallery中,通过开发者工具查看XHR请求地址为:
https://tuchong.com/rest/tags/美女/posts?page=1&count=20&order=weekly&before_timestamp=
参数很简单,page是页码,count是每页图集数量,order是排序,before_timestamp为空,图虫因为是推送内容式的网站,因此before_timestamp应该是一个时间值,不同的时间会显示不同的内容,这里我们把它丢弃,不考虑时间直接从最新的页面向前抓取。
请求结果为JSON格式内容,降低了抓取难度,结果如下:
{ "postList": [ { "post_id": "15624611", "type": "multi-photo", "url": "https://weishexi.tuchong.com/15624611/", "site_id": "443122", "author_id": "443122", "published_at": "2017-10-28 18:01:03", "excerpt": "10月18日", "favorites": 4052, "comments": 353, "rewardable": true, "parent_comments": "165", "rewards": "2", "views": 52709, "title": "微风不燥 秋意正好", "image_count": 15, "images": [ { "img_id": 11585752, "user_id": 443122, "title": "", "excerpt": "", "width": 5016, "height": 3840 }, { "img_id": 11585737, "user_id": 443122, "title": "", "excerpt": "", "width": 3840, "height": 5760 }, ... ], "title_image": null, "tags": [ { "tag_id": 131, "type": "subject", "tag_name": "人像", "event_type": "", "vote": "" }, { "tag_id": 564, "type": "subject", "tag_name": "美女", "event_type": "", "vote": "" } ], "favorite_list_prefix": [], "reward_list_prefix": [], "comment_list_prefix": [], "cover_image_src": "https://photo.tuchong.com/443122/g/11585752.webp", "is_favorite": false } ], "siteList": {...}, "following": false, "coverUrl": "https://photo.tuchong.com/443122/ft640/11585752.webp", "tag_name": "美女", "tag_id": "564", "url": "https://tuchong.com/tags/%E7%BE%8E%E5%A5%B3/", "more": true, "result": "SUCCESS"}
新闻热点
疑难解答