1.1 爬虫准备
1.合法性
2.背景调研
(1)检查robot.txt 文件,一般放在域名的一级目录。此文件会提示
爬取改网站的注意事项
例如 https://www.baidu.com/robots.txt
(2)网站地图 ,robot文件里面
3.识别网络爬虫所用的技术
1.安装 builtwith 模块
2. builtwith.parse(url,header..)
4.查看网站的拥有者
1.安装whois 模块
2.whois.whois(域名)
1.2 下载网页
1.简单的下载网页
2.增加异常
3.如果返回码是服务器错误 500-600 之间,重新请求
4.设置用户代理
def download(url ,user_agent='wswp',num_retries=2):
print ("Downloading:",url)
headers={'User_agent':user_agent}
request=urllib.request .Request(url,headers=headers)
try:
html= urllib.request.urlopen(request).read()
except urllib.error.URLError as a:
print("Download error:", hasattr(a,'code'))
html=None
if num_retries>0:
if hasattr(a,'code') and 500<=a.code <600:
return download(url,user_agent,num_retries-1)
return html
5.网站地图获取链接
def crawl_sitemap(url):
sitemape=download(url).decode('utf-8')
#print (sitemape)
links=re.findall('<loc>(.*?)</loc>',sitemape)
return len(links)