#python爬虫实例   爬取新闻#爬取新浪新闻首页中所有的新闻,爬到本地(http://news.sina.com.cn/)#实现过程,先爬首页,通过正则表达式获取所有新闻链接,然后依次爬各新闻,并存储到本地import urllib.requestimport redata=urllib.request.urlopen("http://news.sina.com.cn/").read()data2=data.decode("utf-8","ignore")pat='href="(http://news.sina.com.cn/.*?)"'allurl=re.compile(pat).findall(data2)for i in range(0,10):    try:        print("第"+str(i)+"次爬取")        thisurl=allurl[i]        file="/Users/xubin/myapp/pythonfile/sina/"+str(i)+".html"        urllib.request.urlretrieve(thisurl,file)        print("------成功-------")    except urllib.error.URLError as e:        if hasattr(e,"code"):            print(e.code)        if hasattr(e,"reason"):            print(e.reason)
收藏 打印