gpt4 book ai didi

Python的爬虫框架scrapy用21行代码写一个爬虫

转载 作者:qq735679552 更新时间:2022-09-27 22:32:09 25 4
gpt4 key购买 nike

CFSDN坚持开源创造价值,我们致力于搭建一个资源共享平台,让每一个IT人在这里找到属于你的精彩世界.

这篇CFSDN的博客文章Python的爬虫框架scrapy用21行代码写一个爬虫由作者收集整理,如果你对这篇文章有兴趣,记得点赞哟.

开发说明 。

开发环境:Pycharm 2017.1(目前最新) 。

开发框架:Scrapy 1.3.3(目前最新) 。

目标 。

爬取线报网站,并把内容保存到items.json里 。

页面分析 。

Python的爬虫框架scrapy用21行代码写一个爬虫

根据上图我们可以发现内容都在类为post这个div里 。

下面放出post的代码 。

?
1
2
3
4
5
6
< div class = "post" >
<!-- baidu_tc block_begin: {"action": "DELETE"} -->
< div class = "date" >< span >04月</ span >< span class = "f" >07日</ span ></ div > <!-- baidu_tc block_end -->
< h2 >< a href = "http://www.abckg.com/193.html" rel = "external nofollow" title = "4月7日 淘金币淘里程领取京东签到" rel = "bookmark" target = "_blank" >4月7日 淘金币淘里程领取京东签到</ a >< span >已结束</ span ></ h2 >
< h6 >发布日期: 2017-04-07 | 分类: < a href = "http://www.abckg.com/xunibi" rel = "external nofollow" >虚拟币</ a > | 浏览:125177
</ h6 >< div class = "intro" >< p >淘金币一键领取 http://021.tw/t/ https://www.chaidu.com/App/Web/Taobao-Coin/ 【电脑端30金币】 https://taojinbi.taobao.com/inde ... auto_take=true 【手机端30金币】 http://h5.m.taobao...</ p ></ div ></ div >

实现方法 。

1、定义items 。

?
1
2
3
4
5
class DemoItem(scrapy.Item):
  id = scrapy.Field()
  title = scrapy.Field()
  href = scrapy.Field()
  content = scrapy.Field()

2、新建一个爬虫名为test 。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# -*- coding: utf-8 -*-
import scrapy
from demo.items import DemoItem
from scrapy.http import Request
class TestSpider(scrapy.Spider):
  #定义爬虫的名字和需要爬取的网址
  name = "test"
  allowed_domains = [ "www.abckg.com" ]
  start_urls = [ 'http://www.abckg.com/' ]
  def parse( self , response):
  for resp in response.css( '.post' ):
   #实例化item
   item = DemoItem()
   #把获取到的内容保存到item内
   item[ 'href' ] = resp.css( 'h2 a::attr(href)' ).extract()
   item[ 'title' ] = resp.css( 'h2 a::text' ).extract()
   item[ 'content' ] = resp.css( '.intro p::text' ).extract()
   yield item
  
  #下面是多页面的爬取方法
  urls = response.css( '.pageinfo a::attr(href)' ).extract()
  for url in urls:
   yield Request(url, callback = self .parse)
  categorys = response.css( '.menu li a::attr(href)' ).extract()
  for ct in categorys:
   yield Request(ct, callback = self .parse)

3、修改settings.py,添加以下代码 。

?
1
FEED_EXPORT_ENCODING = 'utf-8'

#运行 。

打开cmd输入 。

?
1
scrapy crawl test -o items.json

Python的爬虫框架scrapy用21行代码写一个爬虫

Python的爬虫框架scrapy用21行代码写一个爬虫

已知bug 。

如果多次运行该爬虫,不会覆盖原有的内容,而是追加数据(好像是scrapy的bug) 。

可拓展内容 。

     1、定时运行爬虫,当检查到网站更新时获取新数据并发邮件通知 。

     2、检测数据是否重复 。

总结 。

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者使用python能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对我的支持.

原文链接:http://lx.nextdev.cn/Python-scrapy-write-a-crawler.html 。

最后此篇关于Python的爬虫框架scrapy用21行代码写一个爬虫的文章就讲到这里了,如果你想了解更多关于Python的爬虫框架scrapy用21行代码写一个爬虫的内容请搜索CFSDN的文章或继续浏览相关文章,希望大家以后支持我的博客! 。

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com