近期写的一个爬虫的Demo,只是简单的用了几个函数。实现了简单的爬取网页的功能(以途牛为例)。

 import urllib2
import re
import urlparse
import robotparser
import datetime
import time class Throttle:
"""
Add a delay to the same domain between two download
"""
def __init__(self, delay):
# amount of delay between download of a domain
self.delay = delay
# timestamp of when a domain was last accessed
self.domains = {} def wait(self, url):
domain = urlparse.urlparse(url).netloc
last_accessed = self.domains.get(domain) if self.delay > 0 and last_accessed is not None:
sleep_sec = self.delay - (datetime.datetime.now() - last_accessed).seconds if sleep_sec >= 0:
time.sleep(sleep_sec)
print 'sleep: ', sleep_sec, 's'
self.domains[domain] = datetime.datetime.now() def download(url, proxy, user_agent='wawp', num_retries=2):
print 'Downloading:', url
headers = {'User-agent': user_agent}
request = urllib2.Request(url, headers=headers) opener = urllib2.build_opener()
if proxy:
proxy_param = {urlparse.urlparse(url).scheme: proxy}
opener.add_handler(urllib2.ProxyHandler(proxy_param))
try:
html = opener.open(request).read()
except urllib2.URLError as e:
print 'Downloading error:', e.reason, '\n'
html = ''
if num_retries > 0:
if hasattr(e, 'code') and 500 <= e.code < 600:
return download(url, proxy, user_agent, num_retries - 1)
return html def get_links(html, regstr=r'http:\/\/[^w].*\.tuniu\.com'):
reg = regstr
rexp = re.compile(reg)
return re.findall(rexp, html) def deduplicate_list(inputList):
new_list = []
for x in inputList:
if x not in new_list:
new_list.append(x)
return new_list def crawl_sitemap(url):
sitemap = download(url)
links = get_links(sitemap)
print 'before links are : ', links
newlinks = deduplicate_list(links)
print 'after links are : ', newlinks for link in newlinks:
print link
download(link) def get_robot(url):
rp = robotparser.RobotFileParser()
rp.set_url(urlparse.urljoin(url, 'robots.txt'))
rp.read()
return rp def link_crawler(seed_url, max_depth=3, link_regex=r'http:\/\/[^w][^"]*\.tuniu\.com', delay=1, proxy=None):
# For robots.txt check install
rp = get_robot(seed_url)
# init vars
throttle = Throttle(delay)
crwal_queue = [seed_url]
seen = {seed_url: 0} while crwal_queue:
url = crwal_queue.pop() depth = seen[url]
if depth != max_depth: if rp.can_fetch('heimaojingzhang', url): # here just for joking
throttle.wait(url)
html = download(url, proxy)
# print 'down func ', url
for link in get_links(html, link_regex):
link = urlparse.urljoin(seed_url, link)
if link not in seen:
seen[link] = depth + 1
crwal_queue.append(link)
else:
print 'Blocked by robot.txt ', url # TODO:
# fix bugs: (in regex) done on : 2017/09/23 23:16
# delay: done on : 2017/09/24 21:36
# proxy
# depth: done on : 2017/09/23 23:10 if __name__ == '__main__':
link_crawler('http://www.tuniu.com/corp/sitemap.shtml', link_regex=r'http:\/\/www\.tuniu\.com\/guide\/[^"]*')
# html = download('http://www.tuniu.com/corp/sitemap.shtml')
# print html

python爬虫入门学习的更多相关文章

  1. Python爬虫入门一之综述

    大家好哈,最近博主在学习Python,学习期间也遇到一些问题,获得了一些经验,在此将自己的学习系统地整理下来,如果大家有兴趣学习爬虫的话,可以将这些文章作为参考,也欢迎大家一共分享学习经验. Pyth ...

  2. 2.Python爬虫入门二之爬虫基础了解

    1.什么是爬虫 爬虫,即网络爬虫,大家可以理解为在网络上爬行的一直蜘蛛,互联网就比作一张大网,而爬虫便是在这张网上爬来爬去的蜘蛛咯,如果它遇到资源,那么它就会抓取下来.想抓取什么?这个由你来控制它咯. ...

  3. 1.Python爬虫入门一之综述

    要学习Python爬虫,我们要学习的共有以下几点: Python基础知识 Python中urllib和urllib2库的用法 Python正则表达式 Python爬虫框架Scrapy Python爬虫 ...

  4. Python爬虫入门二之爬虫基础了解

    1.什么是爬虫 爬虫,即网络爬虫,大家可以理解为在网络上爬行的一直蜘蛛,互联网就比作一张大网,而爬虫便是在这张网上爬来爬去的蜘蛛咯,如果它遇到资源,那么它就会抓取下来.想抓取什么?这个由你来控制它咯. ...

  5. 转 Python爬虫入门二之爬虫基础了解

    静觅 » Python爬虫入门二之爬虫基础了解 2.浏览网页的过程 在用户浏览网页的过程中,我们可能会看到许多好看的图片,比如 http://image.baidu.com/ ,我们会看到几张的图片以 ...

  6. 转 Python爬虫入门一之综述

    转自: http://cuiqingcai.com/927.html 静觅 » Python爬虫入门一之综述 首先爬虫是什么? 网络爬虫(又被称为网页蜘蛛,网络机器人,在FOAF社区中间,更经常的称为 ...

  7. python爬虫入门02:教你通过 Fiddler 进行手机抓包

    哟~哟~哟~ hi起来 everybody 今天要说说怎么在我们的手机抓包 通过 python爬虫入门01:教你在Chrome浏览器轻松抓包 我们知道了 HTTP 的请求方式 以及在 Chrome 中 ...

  8. python爬虫入门01:教你在 Chrome 浏览器轻松抓包

    通过 python爬虫入门:什么是爬虫,怎么玩爬虫? 我们知道了什么是爬虫 也知道了爬虫的具体流程 那么在我们要对某个网站进行爬取的时候 要对其数据进行分析 就要知道应该怎么请求 就要知道获取的数据是 ...

  9. Python爬虫入门有哪些基础知识点

    1.什么是爬虫 爬虫,即网络爬虫,大家可以理解为在网络上爬行的一直蜘蛛,互联网就比作一张大网,而爬虫便是在这张网上爬来爬去的蜘蛛咯,如果它遇到资源,那么它就会抓取下来.想抓取什么?这个由你来控制它咯. ...

随机推荐

  1. Knowledge_SPA——精研查找算法

    首先保证这一篇分析查找算法的文章,气质与大部分搜索引擎搜索到的文章不同,主要体现在代码上面,会更加高级,会结合到很多之前研究过的内容,例如设计模式,泛型等.这也与我的上一篇面向程序员编程--精研排序算 ...

  2. [转载] kill命令

    转载自http://www.cnblogs.com/peida/archive/2012/12/20/2825837.html Linux中的kill命令用来终止指定的进程(terminate a p ...

  3. 设计模式的征途—11.外观(Facade)模式

    在软件开发中,有时候为了完成一项较为复杂的功能,一个类需要和多个其他业务类交互,而这些需要交互的业务类经常会作为一个完整的整体出现,由于涉及的类比较多,导致使用时代码较为复杂,此时,特别需要一个类似服 ...

  4. OpenTSDB - 分布式可扩展的监控系统

    OpenTSDB - A Distributed, Scalable Monitoring System http://opentsdb.net/getting-started.html http:/ ...

  5. 【架构研习】欲善其事先利其器-Robot Framework实战演练之框架的选择

    (原创文章,转载请注明出处.) 之前有提到过,自己曾基于公司业务系统从无到有码过一套测试框架,但由于开发时的思想同时受限于公司业务及框架的适用性上,导致最终虽然框架可完美支持业务,但在易用性.兼容性及 ...

  6. mac 安装protobuf,并编译

    因公司接口协议是PB文件,需要将 PB 编译成JAVA文件,且MAC 电脑,故整理并分享MAC安装 google 下的protobuf 文件   MAC 安装protobuf 流程 1.下载 http ...

  7. app打包常用操作

    1.修改appId android:打开build.gradle文件 找到defaultConfig{applicationId 'ceshi'} 修改测试.android studio会提示. Gr ...

  8. Kafka设计解析(八)- Exactly Once语义与事务机制原理

    原创文章,首发自作者个人博客,转载请务必将下面这段话置于文章开头处. 本文转发自技术世界,原文链接 http://www.jasongj.com/kafka/transaction/ 写在前面的话 本 ...

  9. JavaScript DOM 编程艺术(1)---> JavaScript语法

    一.  JavaScript语法目录 语法 操作 条件语句 循环语句 函数 对象 二.  具体内容 2.1 语法 javaScript代码要通过HTML/XHTML文档才能执行.可以有两种方式完成这一 ...

  10. Less的内置函数

    杂项函数 color 解析颜色,将代表颜色的字符串转换为颜色值. 参数: string: 代表颜色值的字符串. 返回值: color 案例: color("#aaa"); 输出: ...