上一篇文章中我们介绍了爬虫的实现,及爬虫爬取数据的功能,这里会遇到几个问题,比方站点中robots.txt文件,里面有禁止爬取的URL。还有爬虫是否支持代理功能。及有些站点对爬虫的风控措施。设计的爬虫下载限速功能。

1、解析robots.txt

首先,我们须要解析robots.txt文件。以避免下载禁止爬取的URL。适用Python自带的robotparser模块,就能够轻松的完毕这项工作,如以下的代码。

robotparser模块首先载入robots.txt文件。然后通过can_fetch()函数确定指定的用户代理是否同意訪问网页。

def get_robots(url):
"""Initialize robots parser for this domain
"""
rp = robotparser.RobotFileParser()
rp.set_url(urlparse.urljoin(url, '/robots.txt'))
rp.read()
return rp

为了将该功能集成到爬虫中,我们须要在crawl循环中加入该检查。

while crawl_queue:
url = crawl_queue.pop()
# check url passes robots.txt restrictions
if rp.can_fetch(user_agent,url):
...
else:
print 'Blocked by robots.txt:',url

2、支持代理

有时我们须要使用代理訪问某个站点。比方,Netflix屏蔽了美国以外的大多数国家。

使用urllib2支持代理并没有想象的那么easy(能够尝试使用更友好的Python HTTP 模块requests来实现该功能)以下是使用urllib2支持代理的代码。

proxy = …

opener = urllib2.build_opener()

proxy_params = {urlparse.urlparse(url).scheme:proxy}

opener.add_header(urllib2.ProxyHandler(proxy_params))

response = opener.open(request)

以下是集成了该功能的新版本号download函数。

def download(url, headers, proxy, num_retries, data=None):
print 'Downloading:', url
request = urllib2.Request(url, data, headers)
opener = urllib2.build_opener()
if proxy:
proxy_params = {urlparse.urlparse(url).scheme: proxy}
opener.add_handler(urllib2.ProxyHandler(proxy_params))
try:
response = opener.open(request)
html = response.read()
code = response.code
except urllib2.URLError as e:
print 'Download error:', e.reason
html = ''
if hasattr(e, 'code'):
code = e.code
if num_retries > 0 and 500 <= code < 600:
# retry 5XX HTTP errors
html = download(url, headers, proxy, num_retries - 1, data)
else:
code = None
return html

3、下载限速

假设我们爬取站点的速度过快,就会面临被封禁或是造成server过载的风险。为了减少这些风险,我们能够在两次下载之间加入延时,从而对爬虫限速。以下是实现了该功能的类的代码。

class Throttle:
"""Throttle downloading by sleeping between requests to same domain
"""
def __init__(self, delay):
# amount of delay between downloads for each domain
self.delay = delay
# timestamp of when a domain was last accessed
self.domains = {} def wait(self, url):
"""Delay if have accessed this domain recently
"""
domain = urlparse.urlsplit(url).netloc
last_accessed = self.domains.get(domain)
if self.delay > 0 and last_accessed is not None:
sleep_secs = self.delay - (datetime.now() - last_accessed).seconds
if sleep_secs > 0:
time.sleep(sleep_secs)
self.domains[domain] = datetime.now()
Throttle类记录了每一个域名上次訪问的时间。假设当前时间距离上次訪问时间小于指定延时。则运行睡眠操作。我们能够在每次下载之前调用Throttle对爬虫进行限速。

4、避免爬虫陷阱

眼下,我们的爬虫会跟踪全部之前没有訪问过的链接。

可是。一些站点会动态生成页面内容,这样就会出现无限多的网页。

比方,站点有一个在线日历功能。提供了能够訪问下一个月或下一年的链接,那么下个月的页面中相同会有訪问再下个月的链接。这样页面就会无止境的链接下去。这样的情况成为爬虫陷阱。

想要避免陷入爬虫陷阱。一个简单的方法是积累到达当前网页经过了多少个链接,也就是深度。当到达最大深度时,爬虫就不再向对列中加入该网页中的链接了。

要实现这一功能,我们须要改动seen变量。该变量原先仅仅记录訪问过的网页链接,如今改动为一个字典,添加了页面深度的记录。

def link_crawler(…,max_length = 2):

max_length = 2

seen = {}



depth = seen[url]

if depth != max_depth:

for link in links:

if link not in seen:

seen[link] = depth + 1

crawl_queue.qppend(link)

如今有了这一功能,我们就有信心爬虫的终于一定能够完毕。假设想要禁用该功能。仅仅须要将max_depth设为一个负数就可以,此时当前深度永远不会与之相等。

终于版本号

import re
import urlparse
import urllib2
import time
from datetime import datetime
import robotparser
import Queue
from scrape_callback3 import ScrapeCallback def link_crawler(seed_url, link_regex=None, delay=5, max_depth=-1, max_urls=-1, headers=None, user_agent='wswp',
proxy=None, num_retries=1, scrape_callback=None):
"""Crawl from the given seed URL following links matched by link_regex
"""
# the queue of URL's that still need to be crawled
crawl_queue = [seed_url]
# the URL's that have been seen and at what depth
seen = {seed_url: 0}
# track how many URL's have been downloaded
num_urls = 0
rp = get_robots(seed_url)
throttle = Throttle(delay)
headers = headers or {}
if user_agent:
headers['User-agent'] = user_agent while crawl_queue:
url = crawl_queue.pop()
depth = seen[url]
# check url passes robots.txt restrictions
if rp.can_fetch(user_agent, url):
throttle.wait(url)
html = download(url, headers, proxy=proxy, num_retries=num_retries)
links = []
if scrape_callback:
links.extend(scrape_callback(url, html) or []) if depth != max_depth:
# can still crawl further
if link_regex:
# filter for links matching our regular expression
links.extend(link for link in get_links(html) if re.match(link_regex, link)) for link in links:
link = normalize(seed_url, link)
# check whether already crawled this link
if link not in seen:
seen[link] = depth + 1
# check link is within same domain
if same_domain(seed_url, link):
# success! add this new link to queue
crawl_queue.append(link) # check whether have reached downloaded maximum
num_urls += 1
if num_urls == max_urls:
break
else:
print 'Blocked by robots.txt:', url class Throttle:
"""Throttle downloading by sleeping between requests to same domain
""" def __init__(self, delay):
# amount of delay between downloads for each domain
self.delay = delay
# timestamp of when a domain was last accessed
self.domains = {} def wait(self, url):
"""Delay if have accessed this domain recently
"""
domain = urlparse.urlsplit(url).netloc
last_accessed = self.domains.get(domain)
if self.delay > 0 and last_accessed is not None:
sleep_secs = self.delay - (datetime.now() - last_accessed).seconds
if sleep_secs > 0:
time.sleep(sleep_secs)
self.domains[domain] = datetime.now() def download(url, headers, proxy, num_retries, data=None):
print 'Downloading:', url
request = urllib2.Request(url, data, headers)
opener = urllib2.build_opener()
if proxy:
proxy_params = {urlparse.urlparse(url).scheme: proxy}
opener.add_handler(urllib2.ProxyHandler(proxy_params))
try:
response = opener.open(request)
html = response.read()
code = response.code
except urllib2.URLError as e:
print 'Download error:', e.reason
html = ''
if hasattr(e, 'code'):
code = e.code
if num_retries > 0 and 500 <= code < 600:
# retry 5XX HTTP errors
html = download(url, headers, proxy, num_retries - 1, data)
else:
code = None
return html def normalize(seed_url, link):
"""Normalize this URL by removing hash and adding domain
"""
link, _ = urlparse.urldefrag(link) # remove hash to avoid duplicates
return urlparse.urljoin(seed_url, link) def same_domain(url1, url2):
"""Return True if both URL's belong to same domain
"""
return urlparse.urlparse(url1).netloc == urlparse.urlparse(url2).netloc def get_robots(url):
"""Initialize robots parser for this domain
"""
rp = robotparser.RobotFileParser()
rp.set_url(urlparse.urljoin(url, '/robots.txt'))
rp.read()
return rp def get_links(html):
"""Return a list of links from html
"""
# a regular expression to extract all links from the webpage
webpage_regex = re.compile('<a[^>]+href=["\'](.*?)["\']', re.IGNORECASE)
# list of all links from the webpage
return webpage_regex.findall(html) if __name__ == '__main__':
# link_crawler('http://example.webscraping.com', '/(index|view)', delay=0, num_retries=1, user_agent='BadCrawler')
# link_crawler('http://example.webscraping.com', '/(index|view)', delay=0, num_retries=1, max_depth=1,
# user_agent='GoodCrawler')
link_crawler('http://fund.eastmoney.com',r'/fund.html#os_0;isall_0;ft_;pt_1',max_depth=-1,scrape_callback=ScrapeCallback

认为好。就打赏下小编吧~

python爬虫高级功能的更多相关文章

  1. Python爬虫入门教程 58-100 python爬虫高级技术之验证码篇4-极验证识别技术之一

    目录 验证码类型 官网最新效果 找个用极验证的网站 拼接验证码图片 编写自动化代码 核心run方法 模拟拖动方法 图片处理方法 初步运行结果 拼接图 图片存储到本地 @ 验证码类型 今天要搞定的验证码 ...

  2. Python爬虫入门教程 57-100 python爬虫高级技术之验证码篇3-滑动验证码识别技术

    滑动验证码介绍 本篇博客涉及到的验证码为滑动验证码,不同于极验证,本验证码难度略低,需要的将滑块拖动到矩形区域右侧即可完成. 这类验证码不常见了,官方介绍地址为:https://promotion.a ...

  3. Python爬虫入门教程 56-100 python爬虫高级技术之验证码篇2-开放平台OCR技术

    今日的验证码之旅 今天你要学习的验证码采用通过第三方AI平台开放的OCR接口实现,OCR文字识别技术目前已经比较成熟了,而且第三方比较多,今天采用的是百度的. 注册百度AI平台 官方网址:http:/ ...

  4. Python爬虫入门教程 55-100 python爬虫高级技术之验证码篇

    验证码探究 如果你是一个数据挖掘爱好者,那么验证码是你避免不过去的一个天坑,和各种验证码斗争,必然是你成长的一条道路,接下来的几篇文章,我会尽量的找到各种验证码,并且去尝试解决掉它,中间有些技术甚至我 ...

  5. python 函数高级功能

    闭包 我们可以将闭包理解为一种特殊的函数,这种函数由两个函数的嵌套组成,且称之为外函数和内函数,外函数返回值是内函数的引用,此时就构成了闭包. # 闭包 # 外部函数的参数被内部函数引用,内部函数对外 ...

  6. Python爬虫入门教程 59-100 python爬虫高级技术之验证码篇5-极验证识别技术之二

    图片比对 昨天的博客已经将图片存储到了本地,今天要做的第一件事情,就是需要在两张图片中进行比对,将图片缺口定位出来 缺口图片 完整图片 计算缺口坐标 对比两张图片的所有RBG像素点,得到不一样像素点的 ...

  7. Python爬虫之selenium高级功能

    Python爬虫之selenium高级功能 原文地址 表单操作 元素拖拽 页面切换 弹窗处理 表单操作 表单里面会有文本框.密码框.下拉框.登陆框等. 这些涉及与页面的交互,比如输入.删除.点击等. ...

  8. Selenium + PhantomJS + python 简单实现爬虫的功能

    Selenium 一.简介 selenium是一个用于Web应用自动化程序测试的工具,测试直接运行在浏览器中,就像真正的用户在操作一样 selenium2支持通过驱动真实浏览器(FirfoxDrive ...

  9. Python爬虫入门之Urllib库的高级用法

    1.设置Headers 有些网站不会同意程序直接用上面的方式进行访问,如果识别有问题,那么站点根本不会响应,所以为了完全模拟浏览器的工作,我们需要设置一些Headers 的属性. 首先,打开我们的浏览 ...

随机推荐

  1. 可编辑DIV与移动端软键盘兼容性问题汇总

    此文复现的所有兼容性问题均为以下情况: 1. 腾讯X5内核 2. 全屏webview 问题如下: 1. IOS12 中软键盘弹出导致页面顶部截断,并且无法恢复. 解决方法:添加交互事件,调用本地方法, ...

  2. linux基础 用户(组)管理

    修改/etc/shadow文件 1.chage -m MINDAYS USERNAME#设置密码修改最小天数2.chage -M MAXDAYS USERNAME#设置密码修改最大天数3.chage ...

  3. vue组件通信那些事儿

    一.说说通信 通信,简言之,交流信息.交流结束后,把信息放在哪里,这是一个值得思考的问题.vue中保存状态有2种方式,组件内的data属性和组件外的vuex的state属性. 1.用state的场景 ...

  4. VMware5.5-vCenter的安装准备及安装

    vSphere 最近公司来了新同事,为了帮助他尽快熟悉VM-vsphere,一块复习了下,并把实验总结为文档. 声明:本例是以王隆杰老师的vsphere5.5教程为基础和线索进行的,由于时间匆忙,可能 ...

  5. 【DWM1000】 code 解密9一 ANCHOR response poll message

    根据上面TAG发送的代码,我直接找到如下代码 case RTLS_DEMO_MSG_TAG_POLL: { if(inst->mode == LISTENER)                  ...

  6. Linux安装Redis和Redis基本操作命令

    01Redis简介 REmote DIctionary Server(Redis) 是一个由Salvatore Sanfilippo写的key-value存储系统. Redis是一个开源的使用ANSI ...

  7. fetch添加超时时间

    fetch添加超时时间 其实为fetch添加超时时间很简单,需要用到Promise.race()方法. Promise.race() 方法将多个Promise包装成一个新的Promise实例. var ...

  8. 屏幕录制软件camtasia studio 8序列号激活

    注册名:TEAM MESMERiZE序列号:3MHCA-5DMCV-H89T8-V8GML-W6FB8 打开hosts文件:C:\Windows\System32\drivers\etc\hosts把 ...

  9. Android笔记--LinearLayout

    LinearLayout 即线性布局,让子元素水平或垂直的排列在 layout中,子元素不会换行,当排到末尾时,剩下的组件将不会被显示出来. LinearLayout 常用的属性及方法: XML属性 ...

  10. redis(六)

    安装包 到中文官网查找客户端代码 联网安装 sudo pip install redis 使用源码安装 unzip redis-py-master.zip cd redis-py-master sud ...