新浪网(sina)新闻链接爬取

目录

一、新闻爬虫需求分析

二、实现思路

三、项目代码实现


一、新闻爬虫需求分析

将新浪新闻首页(http://news.sina.com.cn)所有新闻都爬取到本地。

二、实现思路

1.首先解析网页,查看各条新闻存储位置

2.通过正则表达式获取新闻链接,依次爬取各新闻并存储到本地

 

pat='href="(http://news.sina.com.cn/.*?)">'
#正则表达式,写出每条新闻对应的链接

三、项目代码实现

# -*- coding: utf-8 -*-
#新浪新闻首页新闻爬取
import urllib.request
import re
data=urllib.request.urlopen("http://news.sina.com.cn/").read()
#读取网页内容
data2=data.decode("utf-8","ignore") 
#有很多情况utf-8或者gbk会出现解码失败,更换不是解决办法,加上ignore第二个参数可忽视基本可以永久性解决问题
pat='href="(http://news.sina.com.cn/.*?)">'
allurl=re.compile(pat).findall(data2)
#从data2中匹配出所有是特定网址的网址
for i in range(0,len(allurl)):#for循环进行遍历
    #异常处理,防止系统崩溃,不然程序遇到异常会终止自动结束
    try:
        print("第"+str(i)+"次爬取")
        thisurl=allurl[i]
        file="C:/Users/Administrator/Desktop/urllib/sinanews"+str(i)+".html"
         #存储到本地文件
        urllib.request.urlretrieve(thisurl,file)
        print("爬取成功")
    except urllib.error.URLError as e:
            #if 语句 判断是否有状态码
            if hasattr(e,"code"):
                print(e.code)
            if hasattr(e,"reason"): 
                print(e.reason)
      

 代码采取了异常处理,增强了程序的健壮性,防止程序因爬取到某条新闻链接产生异常跳出系统,try....except,假设产生异常输出提示语,自动进入下次循环.

猜你喜欢

转载自blog.csdn.net/Analyst128/article/details/81209140