python学习之新闻爬虫(五)

将新浪新闻首页(https://news.sina.com.cn/) 所有新闻爬到本地。
先爬首页,通过正则表达式获取所有新闻链接,然后依次爬取各新闻,并存储到本地

import urllib.request
import re
data=urllib.request.urlopen("https://news.sina.com.cn/").read()
data2=data.decode("utf-8","ignore") #ignore 有错误时忽略
pat='href="(https://news.sina.com.cn/.*?)"'   #(组合),匹配括号内的任意正则表达式,并标识出组合的开始和结尾。匹配完成后,组合的内容可以被获取
allurl=re.compile(pat).findall(data2)
for i in range(0,len(allurl)):
  
  thisurl=allurl[i]
  
  file="f:/pytest/unit/news/"+str(i)+'.html'
  urllib.request.urlretrieve(thisurl,file)
  
  print(thisurl)

爬取CSDN博客首页

import urllib.request
import re
url1='https://blog.csdn.net/'

header=('User-Agent',"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.26 Safari/537.36 Core/1.63.5221.400 QQBrowser/10.0.1125.400")
opener=urllib.request.build_opener()
opener.add_handlers=[header]
data=opener.open(url1).read()
data2=data.decode('utf-8','ignore')

pat='href="(https://blog.csdn.net/.*?)"'
url=re.compile(pat).findall(data2)
for i in range(0,len(url)):
  thisurl=url[i]
  fh=open('f:/pytest/unit/blog.txt','w')
  fh.write(thisurl)
  file='f:/pytest/unit/blog'+str(i)+'.html'
  urllib.request.urlretrieve(thisurl,file)
  
  print(thisurl)
fh.close()

猜你喜欢

转载自blog.csdn.net/weixin_39892788/article/details/89855582