python实现新浪新闻爬虫

1、没有伪装成浏览器进行爬取操作

将爬取的新闻网址保存到文件夹e:/sinanews/中,成功后直接通过浏览器打开。

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)):
    try:
        print('第'+ str(i)+'次爬取')
        thisurl=allurl[i]
        file='e:/sinanews/'+ 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)

2、伪装为浏览器爬取新闻

爬取博客首页的文章:伪装浏览器,循环爬取文章。user_agent需要设置为特定某个浏览器的user-agent

import urllib.request
import re
url='https://blog.csdn.net/'
headers=('User-Agent','User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/17.17134')
opener=urllib.request.build_opener()#添加报头信息
opener.addheaders=[headers]
data=opener.open(url).read()
#data=urllib.request.urlopen('https://blog.csdn.net/').read()
data2=data.decode('utf-8','ignore')#加第二个参数ignore
print(len(data2))
pat ='href="(https://blog.csdn.net/.*?)"'
allurl=re.compile(pat).findall(data2)
for i in range(0,len(allurl)):
    try:
        print('第'+ str(i)+'次爬取')
        thisurl=allurl[i]
        file='e:/sinanews/'+ 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)

第二种方式,将将opener添加到全局,都可以使用。

import urllib.request
import re
url='https://blog.csdn.net/'
headers=('User-Agent','User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/17.17134')
opener=urllib.request.build_opener()#添加报头信息
opener.addheaders=[headers]
urllib.request.install_opener(opener)#将opener添加到全局,urlopen(url)可用
data=urllib.request.urlopen(url).read().decode('utf-8','ignore') 
pat ='<a href="(https://blog.csdn.net/.*?)"'
allurl=re.compile(pat).findall(data)
for i in range(0,len(allurl)):
    try:
        print('第'+ str(i)+'次爬取')
        thisurl=allurl[i]
        file='e:/sinanews/'+ 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)

爬取之后,保存到文件夹中的如图所示。

猜你喜欢

转载自blog.csdn.net/xx20cw/article/details/84306104