400-028-6601
建站资讯

网站建设资讯

为你提供网站建设行业资讯、网站优化知识、主机域名邮箱、网站开发常见问题等。

基于Python的Scrapy爬虫入门:代码详解

一、内容分析

创新互联专注于临西网站建设服务及定制,我们拥有丰富的企业做网站经验。 热诚为您提供临西营销型网站建设,临西网站制作、临西网页设计、临西网站官网定制、微信平台小程序开发服务,打造临西网络公司原创品牌,更为您提供临西网站排名全网营销落地服务。

接下来创建一个爬虫项目,以 图虫网 为例抓取里面的图片。在顶部菜单“发现” “标签”里面是对各种图片的分类,点击一个标签,比如“美女”,网页的链接为:https://tuchong.com/tags/美女/,我们以此作为爬虫入口,分析一下该页面:

打开页面后出现一个个的图集,点击图集可全屏浏览图片,向下滚动页面会出现更多的图集,没有页码翻页的设置。Chrome右键“检查元素”打开开发者工具,检查页面源码,内容部分如下:

 
 
 
  1.  
  2.  
  3.      
  4.  
  5.          
  6.  
  7.             

可以判断每一个li.gallery-item是一个图集的入口,存放在ul.pagelist-wrapper下,div.widget-gallery是一个容器,如果使用 xpath 选取应该是://div[@class=”widget-gallery”]/ul/li,按照一般页面的逻辑,在li.gallery-item下面找到对应的链接地址,再往下深入一层页面抓取图片。

但是如果用类似 Postman 的HTTP调试工具请求该页面,得到的内容是:

 
 
 
  1.  
  2.  
  3.     
 
  •  
  •  

    也就是并没有实际的图集内容,因此可以断定页面使用了Ajax请求,只有在浏览器载入页面时才会请求图集内容并加入div.widget-gallery中,通过开发者工具查看XHR请求地址为:

     
     
     
    1. https://tuchong.com/rest/tags/美女/posts?page=1&count=20&order=weekly&before_timestamp= 

    参数很简单,page是页码,count是每页图集数量,order是排序,before_timestamp为空,图虫因为是推送内容式的网站,因此before_timestamp应该是一个时间值,不同的时间会显示不同的内容,这里我们把它丢弃,不考虑时间直接从***的页面向前抓取。

    请求结果为JSON格式内容,降低了抓取难度,结果如下:

     
     
     
    1. { 
    2.  
    3.   "postList": [ 
    4.  
    5.     { 
    6.  
    7.       "post_id": "15624611", 
    8.  
    9.       "type": "multi-photo", 
    10.  
    11.       "url": "https://weishexi.tuchong.com/15624611/", 
    12.  
    13.       "site_id": "443122", 
    14.  
    15.       "author_id": "443122", 
    16.  
    17.       "published_at": "2017-10-28 18:01:03", 
    18.  
    19.       "excerpt": "10月18日", 
    20.  
    21.       "favorites": 4052, 
    22.  
    23.       "comments": 353, 
    24.  
    25.       "rewardable": true, 
    26.  
    27.       "parent_comments": "165", 
    28.  
    29.       "rewards": "2", 
    30.  
    31.       "views": 52709, 
    32.  
    33.       "title": "微风不燥  秋意正好", 
    34.  
    35.       "image_count": 15, 
    36.  
    37.       "images": [ 
    38.  
    39.         { 
    40.  
    41.           "img_id": 11585752, 
    42.  
    43.           "user_id": 443122, 
    44.  
    45.           "title": "", 
    46.  
    47.           "excerpt": "", 
    48.  
    49.           "width": 5016, 
    50.  
    51.           "height": 3840 
    52.  
    53.         }, 
    54.  
    55.         { 
    56.  
    57.           "img_id": 11585737, 
    58.  
    59.           "user_id": 443122, 
    60.  
    61.           "title": "", 
    62.  
    63.           "excerpt": "", 
    64.  
    65.           "width": 3840, 
    66.  
    67.           "height": 5760 
    68.  
    69.         }, 
    70.  
    71.         ... 
    72.  
    73.       ], 
    74.  
    75.       "title_image": null, 
    76.  
    77.       "tags": [ 
    78.  
    79.         { 
    80.  
    81.           "tag_id": 131, 
    82.  
    83.           "type": "subject", 
    84.  
    85.           "tag_name": "人像", 
    86.  
    87.           "event_type": "", 
    88.  
    89.           "vote": "" 
    90.  
    91.         }, 
    92.  
    93.         { 
    94.  
    95.           "tag_id": 564, 
    96.  
    97.           "type": "subject", 
    98.  
    99.           "tag_name": "美女", 
    100.  
    101.           "event_type": "", 
    102.  
    103.           "vote": "" 
    104.  
    105.         } 
    106.  
    107.       ], 
    108.  
    109.       "favorite_list_prefix": [], 
    110.  
    111.       "reward_list_prefix": [], 
    112.  
    113.       "comment_list_prefix": [], 
    114.  
    115.       "cover_image_src": "https://photo.tuchong.com/443122/g/11585752.webp", 
    116.  
    117.       "is_favorite": false 
    118.  
    119.     } 
    120.  
    121.   ], 
    122.  
    123.   "siteList": {...}, 
    124.  
    125.   "following": false, 
    126.  
    127.   "coverUrl": "https://photo.tuchong.com/443122/ft640/11585752.webp", 
    128.  
    129.   "tag_name": "美女", 
    130.  
    131.   "tag_id": "564", 
    132.  
    133.   "url": "https://tuchong.com/tags/%E7%BE%8E%E5%A5%B3/", 
    134.  
    135.   "more": true, 
    136.  
    137.   "result": "SUCCESS" 
    138.  
    139. } 

    根据属性名称很容易知道对应的内容含义,这里我们只需关心 postlist 这个属性,它对应的一个数组元素便是一个图集,图集元素中有几项属性我们需要用到:

    根据图片浏览页面分析,基本上图片的地址都是这种格式: https://photo.tuchong.com/{site_id}/f/{img_id}.jpg ,很容易通过上面的信息合成。

    二、创建项目

    1. 进入cmder命令行工具,输入workon scrapy 进入之前建立的虚拟环境,此时命令行提示符前会出现(Scrapy) 标识,标识处于该虚拟环境中,相关的路径都会添加到PATH环境变量中便于开发及使用。
    2. 输入 scrapy startproject tuchong 创建项目 tuchong
    3. 进入项目主目录,输入 scrapy genspider photo tuchong.com 创建一个爬虫名称叫 photo (不能与项目同名),爬取 tuchong.com 域名(这个需要修改,此处先输个大概地址),的一个项目内可以包含多个爬虫

    经过以上步骤,项目自动建立了一些文件及设置,目录结构如下:

     
     
     
    1. (PROJECT) 
    2.  
    3. │  scrapy.cfg 
    4.  
    5. │ 
    6.  
    7. └─tuchong 
    8.  
    9.     │  items.py 
    10.  
    11.     │  middlewares.py 
    12.  
    13.     │  pipelines.py 
    14.  
    15.     │  settings.py 
    16.  
    17.     │  __init__.py 
    18.  
    19.     │ 
    20.  
    21.     ├─spiders 
    22.  
    23.     │  │  photo.py 
    24.  
    25.     │  │  __init__.py 
    26.  
    27.     │  │ 
    28.  
    29.     │  └─__pycache__ 
    30.  
    31.     │          __init__.cpython-36.pyc 
    32.  
    33.     │ 
    34.  
    35.     └─__pycache__ 
    36.  
    37.             settings.cpython-36.pyc 
    38.  
    39.             __init__.cpython-36.pyc 

    三、主要代码

    items.py 中创建一个TuchongItem类并定义需要的属性,属性继承自 scrapy.Field 值可以是字符、数字或者列表或字典等等:

     
     
     
    1. import scrapy 
    2.  
    3. class TuchongItem(scrapy.Item): 
    4.  
    5.     post_id = scrapy.Field() 
    6.  
    7.     site_id = scrapy.Field() 
    8.  
    9.     title = scrapy.Field() 
    10.  
    11.     type = scrapy.Field() 
    12.  
    13.     url = scrapy.Field() 
    14.  
    15.     image_count = scrapy.Field() 
    16.  
    17.     images = scrapy.Field() 
    18.  
    19.     tags = scrapy.Field() 
    20.  
    21.     excerpt = scrapy.Field() 
    22.  
    23.     ... 

    这些属性的值将在爬虫主体中赋予。

    spiders\photo.py 这个文件是通过命令 scrapy genspider photo tuchong.com 自动创建的,里面的初始内容如下:

     
     
     
    1. import scrapy 
    2.  
    3. class PhotoSpider(scrapy.Spider): 
    4.  
    5.     name = 'photo' 
    6.  
    7.     allowed_domains = ['tuchong.com'] 
    8.  
    9.     start_urls = ['http://tuchong.com/'] 
    10.  
    11.     def parse(self, response): 
    12.  
    13.         pass 

    爬虫名 name,允许的域名 allowed_domains(如果链接不属于此域名将丢弃,允许多个) ,起始地址 start_urls 将从这里定义的地址抓取(允许多个)

    函数 parse 是处理请求内容的默认回调函数,参数 response 为请求内容,页面内容文本保存在 response.body 中,我们需要对默认代码稍加修改,让其满足多页面循环发送请求,这需要重载 start_requests 函数,通过循环语句构建多页的链接请求,修改后代码如下:

     
     
     
    1. import scrapy, json 
    2.  
    3. from ..items import TuchongItem 
    4.  
    5. class PhotoSpider(scrapy.Spider): 
    6.  
    7.     name = 'photo' 
    8.  
    9.     # allowed_domains = ['tuchong.com'] 
    10.  
    11.     # start_urls = ['http://tuchong.com/'] 
    12.  
    13.  
    14.     def start_requests(self): 
    15.  
    16.         url = 'https://tuchong.com/rest/tags/%s/posts?page=%d&count=20&order=weekly'; 
    17.  
    18.         # 抓取10个页面,每页20个图集 
    19.  
    20.         # 指定 parse 作为回调函数并返回 Requests 请求对象 
    21.  
    22.         for page in range(1, 11): 
    23.  
    24.             yield scrapy.Request(url=url % ('美女', page), callback=self.parse) 
    25.  
    26.  
    27.     # 回调函数,处理抓取内容填充 TuchongItem 属性 
    28.  
    29.     def parse(self, response): 
    30.  
    31.         body = json.loads(response.body_as_unicode()) 
    32.  
    33.         items = [] 
    34.  
    35.         for post in body['postList']: 
    36.  
    37.             item = TuchongItem() 
    38.  
    39.             item['type'] = post['type'] 
    40.  
    41.             item['post_id'] = post['post_id'] 
    42.  
    43.             item['site_id'] = post['site_id'] 
    44.  
    45.             item['title'] = post['title'] 
    46.  
    47.             item['url'] = post['url'] 
    48.  
    49.             item['excerpt'] = post['excerpt'] 
    50.  
    51.             item['image_count'] = int(post['image_count']) 
    52.  
    53.             item['images'] = {} 
    54.  
    55.             # 将 images 处理成 {img_id: img_url} 对象数组 
    56.  
    57.             for img in post.get('images', ''): 
    58.  
    59.                 img_id = img['img_id'] 
    60.  
    61.                 url = 'https://photo.tuchong.com/%s/f/%s.jpg' % (item['site_id'], img_id) 
    62.  
    63.                 item['images'][img_id] = url 
    64.  
    65.             item['tags'] = [] 
    66.  
    67.             # 将 tags 处理成 tag_name 数组 
    68.  
    69.             for tag in post.get('tags', ''): 
    70.  
    71.                 item['tags'].append(tag['tag_name']) 
    72.  
    73.             items.append(item) 
    74.  
    75.         return items 

    经过这些步骤,抓取的数据将被保存在 TuchongItem 类中,作为结构化的数据便于处理及保存。

    前面说过,并不是所有抓取的条目都需要,例如本例中我们只需要 type=”multi_photo 类型的图集,并且图片太少的也不需要,这些抓取条目的筛选操作以及如何保存需要在pipelines.py中处理,该文件中默认已创建类 TuchongPipeline 并重载了 process_item函数,通过修改该函数只返回那些符合条件的 item,代码如下:

     
     
     
    1. import scrapy, json 
    2.  
    3. from ..items import TuchongItem 
    4.  
    5. class PhotoSpider(scrapy.Spider): 
    6.  
    7.     name = 'photo' 
    8.  
    9.     # allowed_domains = ['tuchong.com'] 
    10.  
    11.     # start_urls = ['http://tuchong.com/'] 
    12.  
    13.  
    14.  
    15.     def start_requests(self): 
    16.  
    17.         url = 'https://tuchong.com/rest/tags/%s/posts?page=%d&count=20&order=weekly'; 
    18.  
    19.         # 抓取10个页面,每页20个图集 
    20.  
    21.         # 指定 parse 作为回调函数并返回 Requests 请求对象 
    22.  
    23.         for page in range(1, 11): 
    24.  
    25.             yield scrapy.Request(url=url % ('美女', page), callback=self.parse) 
    26.  
    27.  
    28.  
    29.     # 回调函数,处理抓取内容填充 TuchongItem 属性 
    30.  
    31.     def parse(self, response): 
    32.  
    33.         body = json.loads(response.body_as_unicode()) 
    34.  
    35.         items = [] 
    36.  
    37.         for post in body['postList']: 
    38.  
    39.             item = TuchongItem() 
    40.  
    41.             item['type'] = post['type'] 
    42.  
    43.             item['post_id'] = post['post_id'] 
    44.  
    45.             item['site_id'] = post['site_id'] 
    46.  
    47.             item['title'] = post['title'] 
    48.  
    49.             item['url'] = post['url'] 
    50.  
    51.             item['excerpt'] = post['excerpt'] 
    52.  
    53.             item['image_count'] = int(post['image_count']) 
    54.  
    55.             item['images'] = {} 
    56.  
    57.             # 将 images 处理成 {img_id: img_url} 对象数组 
    58.  
    59.             for img in post.get('images', ''): 
    60.  
    61.                 img_id = img['img_id'] 
    62.  
    63.                 url = 'https://photo.tuchong.com/%s/f/%s.jpg' % (item['site_id'], img_id) 
    64.  
    65.                 item['images'][img_id] = url 
    66.  
    67.  
    68.  
    69.             item['tags'] = [] 
    70.  
    71.             # 将 tags 处理成 tag_name 数组 
    72.  
    73.             for tag in post.get('tags', ''): 
    74.  
    75.                 item['tags'].append(tag['tag_name']) 
    76.  
    77.             items.append(item) 
    78.  
    79.         return items 

    当然如果不用管道直接在 parse 中处理也是一样的,只不过这样结构更清晰一些,而且还有功能更多的FilePipelines和ImagePipelines可供使用,process_item将在每一个条目抓取后触发,同时还有 open_spider 及 close_spider 函数可以重载,用于处理爬虫打开及关闭时的动作。

    注意:管道需要在项目中注册才能使用,在 settings.py 中添加:

     
     
     
    1. ITEM_PIPELINES = { 
    2.  
    3.     'tuchong.pipelines.TuchongPipeline': 300, # 管道名称: 运行优先级(数字小优先) 
    4.  
    5. } 

    另外,大多数网站都有反爬虫的 Robots.txt 排除协议,设置 ROBOTSTXT_OBEY = True 可以忽略这些协议,是的,这好像只是个君子协定。如果网站设置了浏览器User Agent或者IP地址检测来反爬虫,那就需要更高级的Scrapy功能,本文不做讲解。

    四、运行

    返回 cmder 命令行进入项目目录,输入命令:

     
     
     
    1. scrapy crawl photo 

    终端会输出所有的爬行结果及调试信息,并在***列出爬虫运行的统计信息,例如:

     
     
     
    1. [scrapy.statscollectors] INFO: Dumping Scrapy stats: 
    2.  
    3. {'downloader/request_bytes': 491, 
    4.  
    5.  'downloader/request_count': 2, 
    6.  
    7.  'downloader/request_method_count/GET': 2, 
    8.  
    9.  'downloader/response_bytes': 10224, 
    10.  
    11.  'downloader/response_count': 2, 
    12.  
    13.  'downloader/response_status_count/200': 2, 
    14.  
    15.  'finish_reason': 'finished', 
    16.  
    17.  'finish_time': datetime.datetime(2017, 11, 27, 7, 20, 24, 414201), 
    18.  
    19.  'item_dropped_count': 5, 
    20.  
    21.  'item_dropped_reasons_count/DropItem': 5, 
    22.  
    23.  'item_scraped_count': 15, 
    24.  
    25.  'log_count/DEBUG': 18, 
    26.  
    27.  'log_count/INFO': 8, 
    28.  
    29.  'log_count/WARNING': 5, 
    30.  
    31.  'response_received_count': 2, 
    32.  
    33.  'scheduler/dequeued': 1, 
    34.  
    35.  'scheduler/dequeued/memory': 1, 
    36.  
    37.  'scheduler/enqueued': 1, 
    38.  
    39.  'scheduler/enqueued/memory': 1, 
    40.  
    41.  'start_time': datetime.datetime(2017, 11, 27, 7, 20, 23, 867300)} 

    主要关注ERROR及WARNING两项,这里的 Warning 其实是不符合条件而触发的 DropItem 异常。

    五、保存结果

    大多数情况下都需要对抓取的结果进行保存,默认情况下 item.py 中定义的属性可以保存到文件中,只需要命令行加参数 -o {filename} 即可:

     
     
     
    1. scrapy crawl photo -o output.json # 输出为JSON文件 
    2.  
    3. scrapy crawl photo -o output.csv  # 输出为CSV文件

    注意:输出至文件中的项目是未经过 TuchongPipeline 筛选的项目,只要在 parse 函数中返回的 Item 都会输出,因此也可以在 parse 中过滤只返回需要的项目

    如果需要保存至数据库,则需要添加额外代码处理,比如可以在 pipelines.py 中 process_item 后添加:

     
     
     
    1. ... 
    2.  
    3.     def process_item(self, item, spider): 
    4.  
    5.         ... 
    6.  
    7.         else: 
    8.  
    9.             print(item['url']) 
    10.  
    11.             self.myblog.add_post(item) # myblog 是一个数据库类,用于处理数据库操作 
    12.  
    13.         return item 
    14.  
    15. ... 

    为了在插入数据库操作中排除重复的内容,可以使用 item[‘post_id’] 进行判断,如果存在则跳过。


    当前题目:基于Python的Scrapy爬虫入门:代码详解
    分享链接:http://www.hnjierui.cn/article/dhioioo.html

    其他资讯