python爬虫入门学习
近期写的一个爬虫的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爬虫入门学习的更多相关文章
- Python爬虫入门一之综述
大家好哈,最近博主在学习Python,学习期间也遇到一些问题,获得了一些经验,在此将自己的学习系统地整理下来,如果大家有兴趣学习爬虫的话,可以将这些文章作为参考,也欢迎大家一共分享学习经验. Pyth ...
- 2.Python爬虫入门二之爬虫基础了解
1.什么是爬虫 爬虫,即网络爬虫,大家可以理解为在网络上爬行的一直蜘蛛,互联网就比作一张大网,而爬虫便是在这张网上爬来爬去的蜘蛛咯,如果它遇到资源,那么它就会抓取下来.想抓取什么?这个由你来控制它咯. ...
- 1.Python爬虫入门一之综述
要学习Python爬虫,我们要学习的共有以下几点: Python基础知识 Python中urllib和urllib2库的用法 Python正则表达式 Python爬虫框架Scrapy Python爬虫 ...
- Python爬虫入门二之爬虫基础了解
1.什么是爬虫 爬虫,即网络爬虫,大家可以理解为在网络上爬行的一直蜘蛛,互联网就比作一张大网,而爬虫便是在这张网上爬来爬去的蜘蛛咯,如果它遇到资源,那么它就会抓取下来.想抓取什么?这个由你来控制它咯. ...
- 转 Python爬虫入门二之爬虫基础了解
静觅 » Python爬虫入门二之爬虫基础了解 2.浏览网页的过程 在用户浏览网页的过程中,我们可能会看到许多好看的图片,比如 http://image.baidu.com/ ,我们会看到几张的图片以 ...
- 转 Python爬虫入门一之综述
转自: http://cuiqingcai.com/927.html 静觅 » Python爬虫入门一之综述 首先爬虫是什么? 网络爬虫(又被称为网页蜘蛛,网络机器人,在FOAF社区中间,更经常的称为 ...
- python爬虫入门02:教你通过 Fiddler 进行手机抓包
哟~哟~哟~ hi起来 everybody 今天要说说怎么在我们的手机抓包 通过 python爬虫入门01:教你在Chrome浏览器轻松抓包 我们知道了 HTTP 的请求方式 以及在 Chrome 中 ...
- python爬虫入门01:教你在 Chrome 浏览器轻松抓包
通过 python爬虫入门:什么是爬虫,怎么玩爬虫? 我们知道了什么是爬虫 也知道了爬虫的具体流程 那么在我们要对某个网站进行爬取的时候 要对其数据进行分析 就要知道应该怎么请求 就要知道获取的数据是 ...
- Python爬虫入门有哪些基础知识点
1.什么是爬虫 爬虫,即网络爬虫,大家可以理解为在网络上爬行的一直蜘蛛,互联网就比作一张大网,而爬虫便是在这张网上爬来爬去的蜘蛛咯,如果它遇到资源,那么它就会抓取下来.想抓取什么?这个由你来控制它咯. ...
随机推荐
- Vue浅谈
谈Vue 最近在学习Vue相关的知识点并且也做一些练手,就在学习过程中出现的各种坑爹的地方做一个总结!之后再遇到也不会抓瞎. 1.Vue工程的安装 (1)首先先安装node.js这是Vue的运行基础. ...
- Tomcat多域名访问
对于域名解析相信很多小伙伴都了解过,就是我们在万网购买一个域名,比如hpugs.com,然后呢?我们希望域名与我们的服务器绑定,然后通过域名直接访问我们的项目,这就是本篇要和大家一起探讨的问题.下面开 ...
- hive Beeline plus HiveServer2简单使用
HiveServer2是经常与beeline一起使用,可以用jdbc客户端远程连接,一般用于生产环境. 在提供传统客服端的功能之外,还提供其他功能: Beeline连接 1.先在hadoop集群启动H ...
- 如何管理Session(防止恶意共享账号)——理论篇
目录 知识要求 背景 技术原理 如何管理Session remember me的问题 附录 知识要求 有一定的WEB后端开发基础,熟悉Session的用法,以及与Redis.Database的配合 本 ...
- mysql数据库的安装与基本配置
目录 绿色版下载 mysql绿色版(5.7版本的安装与配置) 绿色版下载: mysql官网下载地址:https://www.oracle.com/index.html mysql绿色版(5.7版本的安 ...
- opengl启动过程
GLuint _program = glCreateProgram(); //create shader program GLuint vertShader, fragShader;//顶点着色器,片 ...
- 在LwIP 协议栈移植 Snap 7
本文欢迎引用,转载. 引用,转载请标明出处! 调试完毕源码将上传到GitHub 为了嵌入式系统与STEP 7 PLC 通过S7 协议通讯,尝试移植 Snap 7 到STM32F407 cpu 上. 今 ...
- jQuery中使用$.each()遍历后台响应的json字符串问题
今天在做练习项目的时候,使用$.each()方法遍历后台传过来的json字符串时,chrome浏览器中发现如下问题 Cannot use 'in' operator to search for 'l ...
- C++杂分析
class word{ public: word(){cout<<"word constructure \n";} word(int i){cout<<&q ...
- caffe+opencv3.3dnn模块 完成手写数字图片识别
最近由于项目需要用到caffe,学习了下caffe的用法,在使用过程中也是遇到了些问题,通过上网搜索和问老师的方法解决了,在此记录下过程,方便以后查看,也希望能为和我一样的新手们提供帮助. 顺带附上老 ...