import urllib.request as ur
from urllib.error import URLError,ContentTooShortError,HTTPError
import re
defdownload(url, num_retries=2, user_agent='wswp',charset='utf-8'):print('Downloading:',url)
request=ur.Request(url)#添加请求头(一般添加'Cookies','User-Agent')#默认请求头wswp (Web Scrapying With Python)
request.add_header('User-Agent',user_agent)#运用异常,try...except...处理遇到一些无法控制的错误的情况:try:
resp=ur.urlopen(request)#headers.get_content_charset()得到请求Http响应返回的字符集
cs=resp.headers.get_content_charset()#如果不存在,则采用默认的字符集utf-8ifnot cs:
cs=charset
#decode()表示根据某种编码表示
html=resp.read().decode(cs)except(URLError,ContentTooShortError,HTTPError)as e:#e.reason 输出错误的原因print('Download error:',e.reason)
html=Noneif num_retries>0:#hasattr(object,name)判断对象(objedt)是否包含对应属性(name)ifhasattr(e,'code')and(500<=e.code<600):#一般地说,4XX错误都是发生在请求中的,5XX错误都是发生在服务器端的#重下载,排除由5XX引起的错误,设定重下载次数为num_retriesreturn download(url,num_retries-1)return html
defcrawl_sitemap(url):
sitemap=download(url)#正则表达,查询所有满足条件的内容#?表示关闭贪婪模式,默认使开启的(我的理解是尽可能多的获取同样是数据)
links=re.findall('<loc>(.*?)</loc>',sitemap)for link in links:
html=download(link)print(html)