一:需求与思路

      需求:将新浪新闻的首页的所有新闻爬取到本地   http://news.sina.com.cn/

      思路:首先爬首页,通过正则表达式获取所有的新闻链接,然后依次爬取新闻,并存储到本地。

二:实战

     

urllib实战4--新闻爬虫(020)

运行程序

urllib实战4--新闻爬虫(020)

查看爬取结果:

urllib实战4--新闻爬虫(020)

三:综上代码:

from urllib import request
import re
data=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,len(allurl)):

    try:

         print("这是第"+str(i)+"次爬取")

         thisurl=allurl[i]
         file="G:/BaiduDownload/python网络爬虫/sinanews/"+str(i)+".html"

         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)

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-07-12
  • 2021-12-13
  • 2022-12-23
  • 2021-09-24
  • 2021-05-14
猜你喜欢
  • 2021-11-14
  • 2022-12-23
  • 2021-05-10
  • 2021-07-03
  • 2022-12-23
  • 2021-09-17
相关资源
相似解决方案