Python 爬虫:爬虫攻防 !

对于一般用户而言,网络爬虫是个好工具,它可以方便地从网站上获取自己想要的信息。可对于网站而言,网络爬虫占用了太多的资源,也没可能从这些爬虫获取点击量,增加广告收入。据有关调查研究证明,网络上超过60%以上的访问量都是爬虫造成的,也难怪网站方对网络爬虫恨之入骨,“杀”之而后快了。

网站方采取种种措施拒绝网络爬虫的访问,而网络高手们则毫不示弱,改进网络爬虫,赋予它更强的功能、更快的速度,以及更隐蔽的手段。在这场爬虫与反爬虫的战争中,双方的比分交替领先,最终谁会赢得胜利,大家将拭目以待。

1、创建一般爬虫

我们先写一个小爬虫程序,假设网站方的各种限制,然后再来看看如何破解网站方的限制,让大家自由地使用爬虫工具。网站限制的爬虫肯定不包括我们这种只有几次访问的爬虫。一般来说,小于100次访问的爬虫都无须为此担心,这里的爬虫纯粹是做演示。

以爬取美剧天堂站点为例,使用Scrapy爬虫来爬取最近更新的美剧。进入Scrapy工作目录,创建meiju100项目。执行命令:

cd

cd code/scrapy

scrapy startproject meiju100

cd meiju100

scrapy genspider meiju100Spider meijutt.com

tree meiju100

执行的结果如图1所示。

Python资源共享群:626017123

 

 

 

 

 

图1 tree meiju100项目

修改后的items.py的内容如下:

1 # -*- coding: utf-8 -*-

2

3 # Define here the models for your scraped items

4 #

5 # See documentation in:

6 # http://doc.scrapy.org/en/latest/topics/items.html

7

8 import scrapy

9

10

11 class Meiju100Item(scrapy.Item):

12   # define the fields for your item here like:

13   # name = scrapy.Field()

14   storyName = scrapy.Field()

15   storyState = scrapy.Field()

16   tvStation = scrapy.Field()

17   updateTime = scrapy.Field()

修改后的meiju100Spider.py内容如下:

1 # -*- coding: utf-8 -*-

2 import scrapy

3 from meiju100.items import Meiju100Item

4

5

6 class Meiju100spiderSpider(scrapy.Spider):

7   name = 'meiju100Spider'

8   allowed_domains = ['meijutt.com']

9   start_urls = ['http://meijutt.com/new100.html']

10

11   def parse(self, response):

12     subSelector = response.xpath('//li/div[@class="lasted-num fn-left"]')

13     items = []

14     for sub in subSelector:

15       item = Meiju100Item()

16       item['storyName'] = sub.xpath('../h5/a/text()').extract()[0]

17       try:

18         item['storyState'] = sub.xpath('../span[@class="state1 new100state1"]/font/text()').extract()[0]

19       except IndexError as e:

20         item['storyState'] = sub.xpath('../span[@class="state1 new100state1"]/text()').extract()[0]

21       item['tvStation'] =sub.xpath('../span[@class="mjtv"]/text()').extract()

22       

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值