python爬虫实战之百度新闻爬取

百度新闻信息爬取

序言

 通过对百度新闻标题、链接、日期及来源的爬取,了解使用python语言爬取少量数据的基本方法。

获取在百度新闻中搜索“阿里巴巴”的网页源代码

 为了获得请求头,我们可以在谷歌浏览器中的地址栏中输入about:version,即可获得headers。
在这里插入图片描述
 除了要请求头,我们还要构造url。
在网页输入阿里巴巴,然后找到地址栏的url,通过简化url,得到这样一个url---->https://www.baidu.com/s?tn=news&rtt=1&bsst=1&cl=2&wd=阿里巴巴。
 有了请求头,我们可以编写基本的爬虫代码了,嘻嘻嘻。

import requests
headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3970.5 Safari/537.36'}
url = 'https://www.baidu.com/s?tn=news&rtt=1&bsst=1&cl=2&wd=阿里巴巴'
res = requests.get(url, headers=headers).text
print(res)

得到部分结果如下所示:

// 意见反馈
setTimeout(function(){
var s = document.createElement(“script”);
s.charset=“utf-8”;
s.src=“https://dss1.bdstatic.com/5eN1bjq8AAUYm2zgoY3K/r/www/cache/news/static/protocol/https/global/js/feedback_4acd551.js”;
document.body.appendChild(s);
},0);

编写正则表达式提取新闻信息

有了源代码,下面我们要提取新闻的来源和日期必须要分析一下这个源代码。
在这里插入图片描述

发现该新闻的标题、链接、日期,全都在 《p class=“c-author”》下面,这样我就知道怎么提取了。

import requests
import re
headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3970.5 Safari/537.36'}
url = 'https://www.baidu.com/s?tn=news&rtt=1&bsst=1&cl=2&wd=阿里巴巴'
res = requests.get(url, headers=headers).text
p_info = '<p class="c-author">(.*?)</p>'
info = re.findall(p_info, res, re.S)
print(info)

代码结果含有\n、\t、&nbsp ;
在这里插入图片描述
同理,我们使用同样的方法利用正则表达式获得具体的标题、链接。

import requests
import re
headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3970.5 Safari/537.36'}
url = 'https://www.baidu.com/s?tn=news&rtt=1&bsst=1&cl=2&wd=阿里巴巴'
res = requests.get(url, headers=headers).text
p_href = '<h3 class="c-title">.*?<a href="(.*?)"'
href = re.findall(p_href, res, re.S)
p_title = '<h3 class="c-title">.*?>(.*?)</a>'
title = re.findall(p_title, res, re.S)
print("链接是:", '\n', href)
print("标题是:", '\n', title)

结果:
在这里插入图片描述

数据清洗并打印输出

import requests
import re
headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3970.5 Safari/537.36'}
url = 'https://www.baidu.com/s?tn=news&rtt=1&bsst=1&cl=2&wd=阿里巴巴'
res = requests.get(url, headers=headers).text
p_info = '<p class="c-author">(.*?)</p>'
info = re.findall(p_info, res, re.S)
# 新闻来源和日期清洗
for i in range(len(info)):
    info[i].split('&nbsp;&nbsp;')
    info[i] = re.sub('<.*?>', '', info[i])
p_href = '<h3 class="c-title">.*?<a href="(.*?)"'
href = re.findall(p_href, res, re.S)
p_title = '<h3 class="c-title">.*?>(.*?)</a>'
title = re.findall(p_title, res, re.S)
# 新闻标题清洗----strip()->除去不需要的空格和换行符、.*?->代替文本之间的所有内容,清洗掉<em></em>
for i in range(len(title)):
    title[i] = title[i].strip()
    title[i] = re.sub('<.*?>', '', title[i])
print("日期是:", '\n', info)
print("链接是:", '\n', href)
print("标题是:", '\n', title)

结果(缺陷:日期没有清洗干净):
在这里插入图片描述

实战完整代码

首先先介绍爬取阿里巴巴公司新闻的标题、日期、链接的完整代码:

# 1.批量爬取一家公司的多页信息
def baidu(page):
    import requests
    import re
    headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36'}
    num = (page - 1) * 10
    url = 'https://www.baidu.com/s?tn=news&rtt=4&bsst=1&cl=2&wd=阿里巴巴&Ppn=' + str(num)
    res = requests.get(url, headers=headers).text
    p_info = '<p class="c-author">(.*?)</p>'
    p_href = '<h3 class="c-title">.*?<a href="(.*?)"'
    p_title = '<h3 class="c-title">.*?>(.*?)</a>'
    info = re.findall(p_info, res, re.S)
    href = re.findall(p_href, res, re.S)
    title = re.findall(p_title, res, re.S)
    source = []  # 先创建两个空列表来储存等会分割后的来源和日期
    date = []
    for i in range(len(info)):
        title[i] = title[i].strip()
        title[i] = re.sub('<.*?>', '', title[i])
        info[i] = re.sub('<.*?>', '', info[i])
        source.append(info[i].split('&nbsp;&nbsp;')[0])
        date.append(info[i].split('&nbsp;&nbsp;')[1])
        source[i] = source[i].strip()
        date[i] = date[i].strip()
        print(str(i + 1) + '.' + title[i] + '(' + date[i] + '-' + source[i] + ')')
        print(href[i])
for i in range(10):  # i是从0开始的序号,所以下面要写成i+1
    baidu(i+1)
    print('第' + str(i+1) + '页爬取成功')

结果:
在这里插入图片描述
然后介绍爬取多家公司新闻的标题、日期、链接的代码:

import requests
import re
def baidu(company):
    headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36'}
    url = 'https://www.baidu.com/s?tn=news&rtt=1&bsst=1&cl=2&wd=' + company
    res = requests.get(url, headers=headers).text
    p_info = '<p class="c-author">(.*?)</p>'
    p_href = '<h3 class="c-title">.*?<a href="(.*?)"'
    p_title = '<h3 class="c-title">.*?>(.*?)</a>'
    info = re.findall(p_info, res, re.S)
    href = re.findall(p_href, res, re.S)
    title = re.findall(p_title, res, re.S)
    source = []  # 先创建两个空列表来储存等会分割后的来源和日期
    date = []
    for i in range(len(info)):
        title[i] = title[i].strip()
        title[i] = re.sub('<.*?>', '', title[i])
        info[i] = re.sub('<.*?>', '', info[i])
        source.append(info[i].split('&nbsp;&nbsp;')[0])
        date.append(info[i].split('&nbsp;&nbsp;')[1])
        source[i] = source[i].strip()
        date[i] = date[i].strip()
        print(str(i + 1) + '.' + title[i] + '(' + date[i] + '-' + source[i] + ')')
        print(href[i])
while True:  # 24小时不间断爬取
    companys = ['华能信托', '阿里巴巴', '万科集团', '百度', '腾讯', '京东']
    for i in companys:
        try:
            baidu(i)
            print(i + '百度新闻爬取成功')
        except:
            print(i + '百度新闻爬取失败')

部分结果如下图所示:
在这里插入图片描述

发布了9 篇原创文章 · 获赞 67 · 访问量 5683
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章