笔记之《用python写网络爬虫》

1 .3 背景调研

robots. txt

 

Robots协议(也称为爬虫协议、机器人协议等)的全称是“网络爬虫排除标准”(Robots Exclusion Protocol),网站通过Robots协议告诉搜索引擎哪些页面可以抓取,哪些页面不能抓取。

WHOIS

whois是用来查询域名的IP以及所有者等信息的传输协议。简单说,whois就是一个用来查询域名是否已经被注册,以及注册域名的详细信息的数据库(如域名所有人、域名注册商)。

1.3.1 检查robots.txt

  crawler英[ˈkrɔ:lə(r)]
  美[ˈkrɔlɚ]
  n.爬行者,爬行动物

1.3.4 识别网站所用技术

检查网站 构建的技术类型builtwith 模块

 

>> import builtwith
>> builtwith.parse('http://exaple.webscraping.com') 

1.3.5 寻找网站所有者 

为了找到网站的所有者,我们可以使用WHOIS协议查询域名的注册者是谁 

pip install python-whois

1.4 编写第一个网络爬虫

· 爬取网站地图;
· 遍历每个网页的数据库ID;
· 跟踪网页链接  

1.4.1 下载网页 

4xx 错误发生在请求存在问题时,而5xx 错误则发生在服务端存在问题时。

1 . 重试下载

2. 设置用户代理 

import urllib2

def download(url,user_agent='wswp',num_retries = 2):
url = 'http://httpstat.us/500'
print 'Downloading',url
headers = {User-agent:user_agent}
request = urllib2.Request(url,headers = headers)

try:
html = urllib2.urlopen(url).read()
except URLError as e:
print 'Downloading error',e.reason
html = None
if num_retries > 0:
if hasattr(e,'code') and 500<=e.code<600:
return download(url,num_retries-1)
return html

if __name__ == '__main__':
download('http://httpstat.us/500',num_retries =2)

注:1.NameError: global name 'User' is not defined

  2.hasattr(object, name)---作用:判断对象object是否包含名为name的特性

  3.recursively   递归的 

1.4.2 网站地图爬虫

import urllib2


def crawel_sitemap(url):
sitemap = download(url)
links = re.findall('<loc>(.*?)<./loc>',sitemap)

for link in links:
html = download(link)

if __name__ == '__main__':
crawel_sitemap('http://exale.webscraping.com/sitemap.xl')

注:1. .*?   *? 重复任意次,但尽可能少重复--非贪婪匹配

  2.extact    英[ˈekstrækt]  美[ɪkˈstrækt]

          vt.提取; (费力地) 拔出; 选取; 获得;

  3.NameError: global name 'download' is not defined

 

 

 

 

posted @ 2017-02-10 15:01  Norwegian-Wood  阅读(1507)  评论(0编辑  收藏  举报