爬虫 下载页面

简介

爬虫下载页面

代码

简易下载

#!/usr/bin/env python
#coding=utf-8
import urllib2def download(url):print('Download:',url)try:html = urllib2.urlopen(url).read()except urllib2.URLError as e:print('Download error:', e.reason)html = Nonereturn htmlif __name__ == '__main__':download('http://www.baidu.com')

似乎并没有把百度的html 下载下来

多次尝试下载 5XX服务器错误 并设置 代理

很多网站都不喜欢被爬虫程序访问,但又没有办法完全禁止,于是就设置了一些反爬策略。比如User Agent,中文名为用户代理,简称UA。User Agent存放于Headers中,服务器就是通过查看Headers中的User Agent来判断是谁在访问。
通过不同的浏览器访问,会有不同的User Agent,如果爬虫不设置的话,很容易被识别出来,就会被限制访问。一般的做法是收集很多不同的User Agent,然后随机使用。
def download(url, user_agent='wswp', num_retries=2):print 'Downloading:', urlheaders = {'User-agent':user_agent}request = urllib2.Request(url, headers=headers)try:html = urllib2.urlopen(request).read()except urllib2.URLError as e:print('Download error:', e.reason)html = Noneif num_retries > 0:if hasattr(e, 'code') and 500 <= e.code < 600:#retyr 5XX HTTP errorsreturn download(url, user_agent, num_retries-1)return html

使用网站地图下载相关的页面

def crawl_sitemap(url):# download the sitemap filesitemap = download(url)# extract the sitemap linkslinks = re.findall('<loc>(.*?)</loc>', sitemap)# download each linkfor link in links:html = download(link)print link

网站可能会把前面的字符串忽略然后可以只用后面的数字

def crawl_string():for page in itertools.count(1):url = 'http://example.webscraping.com/view/-%d' % pagehtml = download(url)if ( html is None):breakelse:pass

网站通过一个页面的链接下载

def get_links(html):webpage_regex = re.compile('<a[^>]+href=["\'](.*?)["\']',re.IGNORECASE)return webpage_regex.findall(html)def link_crawler(seed_url, link_regex):crawl_queue = [seed_url]# keep track which URL's have seen beforeseen = set(crawl_queue)while crawl_queue:url = crawl_queue.pop()html = download(url)print "getlinks", get_links(html)for link in get_links(html):if re.match(link_regex, link):link = urlparse.urljoin(seed_url, link)if link not in seen:seen.add(link)crawl_queue.append(link)if __name__ == '__main__':link_crawler('http://example.webscraping.com', '/places/default/(index|view)')

支持对 robots.txt 的解析

def link_crawler(seed_url, link_regex):rp = robotparser.RobotFileParser()rp.set_url(seed_url+'/robots.txt')rp.read()crawl_queue = [seed_url]# keep track which URL's have seen beforeseen = set(crawl_queue)while crawl_queue:url = crawl_queue.pop()user_agent = 'wswp'if rp.can_fetch(user_agent, url):html = download(url)print "getlinks", get_links(html)for link in get_links(html):if re.match(link_regex, link):link = urlparse.urljoin(seed_url, link)if link not in seen:seen.add(link)crawl_queue.append(link)else:print 'Blocked by robots.txt:', url

代理

def link_crawler(seed_url, link_regex, proxy=False):if proxy: # 暂时无法代理proxy_info={'host':'106.12.38.133','port':22}# We create a handler for the proxyproxy_support = urllib2.ProxyHandler({"http" : "http://%(host)s:%(port)d" % proxy_info})# We create an opener which uses this handler:opener = urllib2.build_opener(proxy_support)# Then we install this opener as the default opener for urllib2:urllib2.install_opener(opener)#如果代理需要验证proxy_info = { 'host' : '106.12.38.133','port' : 20,'user' : 'root','pass' : 'Woaini7758258!'}proxy_support = urllib2.ProxyHandler({"http" : "http://%(user)s:%(pass)s@%(host)s:%(port)d" % proxy_info})opener = urllib2.build_opener(proxy_support)urllib2.install_opener(opener)#htmlpage = urllib2.urlopen("http://sebsauvage.net/").read(200000)rp = robotparser.RobotFileParser()rp.set_url(seed_url+'/robots.txt')rp.read()crawl_queue = [seed_url]# keep track which URL's have seen beforeseen = set(crawl_queue)while crawl_queue:url = crawl_queue.pop()user_agent = 'wswp'if rp.can_fetch(user_agent, url):html = download(url)print "getlinks", get_links(html)for link in get_links(html):if re.match(link_regex, link):link = urlparse.urljoin(seed_url, link)if link not in seen:seen.add(link)crawl_queue.append(link)else:print 'Blocked by robots.txt:', url

下载限速

class Throttle:"""下载延迟 下载之前调用"""def __init__(self, delay):self.delay = delayself.domains()def wait(self, url):domain = urlparse.urlparse(url).netloclast_accessed = self.domains.get(domain)if self.delay > 0 and last_accessed is not None:sleep_secs = self.delay - (datetime.datetime.now() - last_accessed).secondsif sleep_secs > 0:time.sleep(sleep_secs)self.domains[domain] = datetime.datetime.now()

参考链接

https://tieba.baidu.com/p/5832236970

转载于:https://www.cnblogs.com/eat-too-much/p/11560067.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/549492.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

域控制器的强制卸载,Active Directory系列之十四

域控制器的强制卸载上篇博文中我们介绍了如何对域控制器进行常规卸载&#xff0c;本文中我们将介绍如何对域控制器进行强制卸载。为什么需要对域控制器进行强制卸载呢&#xff1f;如果域控制器不能和复制伙伴正常通讯&#xff0c;而且更正无望&#xff0c;那我们就要考虑进行强…

题解 [SHOI2014]概率充电器

前情提要&#xff1a;最近大佬们都在写题解&#xff0c;只有我在咕咕咕。QAQ&#xff1b;明明我都把flag写出来辣&#xff0c;dalao们没看见&#xff0c;然后就被嘲讽了,QAQ 洛谷 树形DP期望&#xff08;讲了两次&#xff0c;菜鸡的我才做&#xff31;&#xff21;&#xff31;…

泛微对协同管理的定义

针对"信息孤岛"、"应用孤岛"和"资源孤岛"&#xff0c;协同管理最主要的三个方面就是要实现信息的协同&#xff0c;业务的协同和资源的协同。泛微的协同管理理念主要体现为三大基本思想&#xff0c;即"信息网状思想"、"业务关联思…

AtCoderGC038B - Sorting a Segment 数据结构 + RMQ

题意&#xff1a;给定一个长度为N的排列&#xff0c;你只能对其中长度为K的连续子序列进行一次从小到大的排序&#xff0c;问&#xff1a;排序之后能形成多少不同的排列&#xff1f; 数据范围&#xff1a; 1 < n, k < 200,000&#xff0c; k < n. -------------------…

添加栏目HyperLink

HyperLink控件&#xff1a;NavigateUrl属性指定跳转页面。页面绑定函数&#xff1a;private void BindPage(){string action Request.QueryString["action"].ToString();if (action "add"){Button1.Text "添加";Label1.Text "添加"…

luogu P2216 [HAOI2007]理想的正方形 递推+ST表

题意&#xff1a;有一个a*b的整数组成的矩阵&#xff0c;现请你从中找出一个n*n的正方形区域&#xff0c;使得该区域所有数中的最大值和最小值的差最小。 数据规模&#xff1a; &#xff08;1&#xff09;矩阵中的所有数都不超过1,000,000,000 &#xff08;2&#xff09;20%的数…

网络管理员必看

值得一看的东西转载于:https://blog.51cto.com/740542/147758

[USACO12MAR]花盆Flowerpot 二分答案+单调队列

题意&#xff1a; 给出N滴水的坐标&#xff0c;y表示水滴的高度&#xff0c;x表示它下落到x轴的位置。 每滴水以每秒1个单位长度的速度下落。你需要把花盆放在x轴上的某个位置&#xff0c;使得从被花盆接着的第1滴水开始&#xff0c;到被花盆接着的最后1滴水结束&#xff0c;之…

jQuery使用手册

jQuery是一款同prototype一样优秀js开发库类&#xff0c;特别是对css和XPath的支持&#xff0c;使我们写js变得更加方便&#xff01;如果你不是个js高手又想写出优 秀的js效果&#xff0c;jQuery可以帮你达到目的&#xff01;下载地址&#xff1a;Starterkit &#xff08;http:…

线程池三种队列使用,SynchronousQueue,LinkedBlockingQueue,ArrayBlockingQueue

使用方法&#xff1a; private static ExecutorService cachedThreadPool new ThreadPoolExecutor(4, Runtime.getRuntime().availableProcessors() * 2, 0, TimeUnit.MILLISECONDS, new SynchronousQueue<>(), r -> new Thread(r, "ThreadTest"));1.Synch…

全志_外部中断

全志_外部中断 平台&#xff1a;全志A64 源码&#xff1a;Android 7.1  Linux3.1 1 #include <linux/init.h>2 #include <linux/module.h>3 #include <linux/fs.h>4 #include <linux/device.h>5 #include <linux/slab.h>6 #include <linux/…

又要开始工作了

“出来混&#xff0c;迟早要还的&#xff01;”&#xff0c;用在工作与休息上也是一样&#xff0c;累积下来的事情真让人身心疲惫&#xff0c;幸好过去的这几天精神还不错&#xff0c;竟然好像要治好我赖床的毛病了。看起来&#xff0c;精神上的压力会比身体上的压力对人的摧残…

[ZJOI2007]时态同步 树形DP

题意&#xff1a;给定一棵N个节点的无根树&#xff0c;每条边都有一个权值V&#xff0c;选取其中一个点作为关键点&#xff0c;你可以任意增加某条边的权值&#xff0c;求使得从关键点出发&#xff0c;到任意一个叶子节点的距离都相同所需要增加的权值和。 数据范围&#xff1a…

apache ,php,mysql的安装

apache.org 下载安装apache php.net 下载php&#xff0c;解压缩&#xff08;注意拷贝dll到windows/system32&#xff0c;并且拷贝php.ini到windows文件夹&#xff0c;修改extention-dir&#xff0c;和对mysql的支持&#xff09; mysql.com 下载安装mysql 安装顺序也是apache&am…

题解P3942_将军令

初始数组忘了赋初值&#xff0c;&#xff0c;&#xff0c;我真是个机灵鬼 还有这题是三倍经验P2279&&P2016&#xff0c;这题的实现思想来自P2279首个题解 luogu 简化题意 给你一棵树&#xff0c;你有一些可以覆盖范围为$k$的障碍物&#xff0c;问最少放几个障碍物可以使…

Hitv8 文件批量重命名工具

本工具用于单文件或批量文件文件名、文件类型扩展名重命名的小工具&#xff0c;欢迎使用&#xff01;使用说明&#xff1a; 1、使用拖放方式&#xff0c;将文件拖入列表框即可 2、可以不输文件名&#xff0c;表示文件名不变&#xff0c;只改类型&#xff1b; 类型也可以自已输入…

[SCOI2009]生日礼物 单调性尺取法

题意&#xff1a;给你n个k种颜色的点&#xff0c;每个点都有坐标和颜色两个属性&#xff0c;选出一个长度尽量短的区间&#xff0c;使得每种颜色的点都在区间内出现。 数据范围&#xff1a; 对于50%的数据&#xff0c; N≤10000&#xff1b; 对于80%的数据&#xff0c; N≤8000…

就算忘了自己也忘不了你

就算忘了自己也忘不了你——代腾飞 2009年4月24日 于成都曾经你说要我紧紧地抱住你让我们的两颗心能紧贴在一起用你的柔情将他们水浮交融彼此渗透到对方的心底我毫不犹豫照做 曾经你说你要用你的脚轻轻放在我的胸膛上你好走到离我心最近的地方让你的脚印镌刻在我的心里成为不…

PJ2018T4 对称二叉树 树形结构

题意&#xff1a;现在给出一棵二叉树&#xff0c;希望你找出它的一棵子树&#xff0c;该子树为对称二叉树&#xff0c;且节点数最多。请输出这棵子树的节点数。对称二叉树满足&#xff1a;将这棵树所有节点的左右子树交换后&#xff0c;新树和原树对应位置的结构相同且点权相等…

Flex的事件(十四)

一、 关于键盘事件<?xml:namespace prefix o ns "urn:schemas-microsoft-com:office:office" />程序响应一个按键或一系列按键并执行一些动作&#xff0c;例如Controlq退出程序。Flex支持所有来自后台操作系统的所有组合键操作&#xff0c;它同样允许你覆…