今天爬一下百度新闻的新闻标题

1.首先分析页面
进入百度新闻百度新闻首页:http://news.baidu.com/
在搜索栏输入需要搜索的内容例如:浙江大学城市学院

再选择搜索的内容为新闻标题点击搜索后页面跳转到以下url:
http://news.baidu.com/ns?word=浙江大学城市学&tn=newstitle&from=news&cl=2&rn=20&ct=0
点击下第二页发现url中增加了pn=20:
http://news.baidu.com/ns?word=浙江大学城市学&pn=20&tn=newstitle&from=news&cl=2&rn=20&ct=0
点击第三页发现pn=40:
http://news.baidu.com/ns?word=浙江大学城市学&pn=20&tn=newstitle&from=news&cl=2&rn=20&ct=0
合理的推断出页数+1,pn+20
2.然后开始分析页面内容
找出比较重要的几个信息新闻标题,新闻来源,新闻时间


以第一条新闻为例,使用浏览器自带的开发者工具(F12)找到其源码中的位置
发现内容写在一个class="result title"的div里面
1<div class="result title" id="1">•
2 <h3 class="c-title">
3 <a href="http://www.eol.cn/zhejiang/zhejiang_news/201802/t20180206_1584845.shtml"
4data-click="{
5 'f0':'77A717EA',
6 'f1':'9F73F1E4',
7 'f2':'4CA6DE6E',
8 'f3':'54E5343F',
9 't':'1521382768'
10 }" target="_blank">
11 <em>浙江大学城市学院</em>2018年“三位一体”综合评价招生章程</a>
12 </h3><div class="c-title-author">中国教育在线 2018年02月06日 23:26</div></div>
3.开始代码实现
通过request模块模拟http访问,lxml进行xpath解析
1from lxml import etree
2import requests
3import json
首先写一个获取页面信息的函数:
1def get_news(url):
2 item = {}
3 #获取页面源码
4 res = requests.get(url).text
5 html = etree.HTML(res)
6 #将class="result title"的内容存储成一个列表对象
7 nodes = html.xpath('//*[@class="result title"]')
8 #遍历对象并取出对象下面的文字内容text()
9 for node in nodes:
10 item['titles'] = ''.join(node.xpath('./h3/a/text()|./h3/a/em/text()'))
11 item['author'] = node.xpath('./*[@class="c-title-author"]/text()')[0].split('\xa0\xa0')[0]
12 item['time'] = node.xpath('./*[@class="c-title-author"]/text()')[0].split('\xa0\xa0')[1]
13 write_data(item)#将内容写入文件
将内容写入文件

1def write_data(item):
2 data = json.dumps(item,ensure_ascii=False) + '\n'
3 with open('new.json','a',encoding='utf-8') as f:
4 f.write(data)
主函数:
1if __name__ == '__main__':
2 word = input('请输入关键字:')
3 pages = input('查看的页数:')
4 for page in range(1,int(pages)+1):
5 print('正在爬取百度新闻中关于「%s」的第「%d」页内容。。。'%(word,page))
6 page = (page-1)*20
7 url='http://news.baidu.com/ns?word=%s&pn=%d&cl=2&ct=1&tn=newstitle&rn=20&ie=utf-8&bt=0&et=0' % (word,page)
8 get_news(url)
以上就完成了一个输入关键字并将内容写入json文件的爬虫


评论与讨论
使用 GitHub 账号留言,评论公开显示。
点评论时间可定位到原评论,在 GitHub 用评论旁的「…」修改或删除自己的留言。