Avoid URLs Matching Any of a Set of Patterns(chilkat/python学习四)过滤url

本文介绍了一种使用Python进行网页爬取的方法,并展示了如何通过设置过滤模式来避免爬取无用或不相关的链接,如特定文件类型和编程语言的链接。
 

大家都知道在页面的超链接中可以连接很多东西,有用的,非常有用的,或是无聊的,无用的,甚至还有错误的,空的,还有莫名其妙的;做个爬虫是很幸苦的,老是被href欺骗感情,遇到这么些个东西你该怎么办呢,过滤掉他,一脚把他踢得远远的,爬虫我的感情是很丰富,但是绝对不喜欢滥交的;

代码:
  1. spider = chilkat.CkSpider()
  2. #  The spider object crawls a single web site at a time.  As you'll see
  3. #  in later examples, you can collect outbound links and use them to
  4. #  crawl the web.  For now, we'll simply spider 10 pages of chilkatsoft.com
  5. spider.Initialize("www.chilkatsoft.com")
  6. #  Add the 1st URL:
  7. spider.AddUnspidered("http://www.chilkatsoft.com/")
  8. #  Avoid URLs matching these patterns:
  9. spider.AddAvoidPattern("*java*")
  10. spider.AddAvoidPattern("*python*")
  11. spider.AddAvoidPattern("*perl*")
  12. #  Begin crawling the site by calling CrawlNext repeatedly.
  13. for i in range(0,10):
  14.     success = spider.CrawlNext()
  15.     if (success == True):
  16.         #  Show the URL of the page just spidered.
  17.         print spider.lastUrl()
  18.         #  The HTML is available in the LastHtml property
  19.     else:
  20.         #  Did we get an error or are there no more URLs to crawl?
  21.         if (spider.get_NumUnspidered() == 0):
  22.             print "No more URLs to spider"
  23.         else:
  24.             print spider.lastErrorText()
  25.     #  Sleep 1 second before spidering the next URL.
  26.     spider.SleepMs(1000)
在这里可以从代码中看到他过滤掉了"java、python、perl",但是在实际中我们应该过滤掉的应该是
"dtd,xsd,javascript,(,zip,rar"等等,看实际情况需要了;

注:在 chilkat中有很多对于url限制功能的函数,具体可以看http://www.example-code.com/python/pythonspider.asp




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值