今天爬一下百度新闻的新闻标题
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里面
<div class="result title" id="1">•
<h3 class="c-title">
<a href="http://www.eol.cn/zhejiang/zhejiang_news/201802/t20180206_1584845.shtml"
data-click="{
'f0':'77A717EA',
'f1':'9F73F1E4',
'f2':'4CA6DE6E',
'f3':'54E5343F',
't':'1521382768'
}" target="_blank">
<em>浙江大学城市学院</em>2018年“三位一体”综合评价招生章程</a>
</h3><div class="c-title-author">中国教育在线 2018年02月06日 23:26</div></div>
3.开始代码实现
通过request模块模拟http访问,lxml进行xpath解析
from lxml import etree
import requests
import json
首先写一个获取页面信息的函数:
def get_news(url):
item = {}
#获取页面源码
res = requests.get(url).text
html = etree.HTML(res)
#将class="result title"的内容存储成一个列表对象
nodes = html.xpath('//*[@class="result title"]')
#遍历对象并取出对象下面的文字内容text()
for node in nodes:
item['titles'] = ''.join(node.xpath('./h3/a/text()|./h3/a/em/text()'))
item['author'] = node.xpath('./*[@class="c-title-author"]/text()')[].split('\xa0\xa0')[]
item['time'] = node.xpath('./*[@class="c-title-author"]/text()')[].split('\xa0\xa0')[]
write_data(item)#将内容写入文件
将内容写入文件
def write_data(item):
data = json.dumps(item,ensure_ascii=False) + '\n'
with open('new.json','a',encoding='utf-8') as f:
f.write(data)
主函数:
if __name__ == '__main__':
word = input('请输入关键字:')
pages = input('查看的页数:')
for page in range(,int(pages)+):
print('正在爬取百度新闻中关于「%s」的第「%d」页内容。。。'%(word,page))
page = (page-1)*
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)
get_news(url)
以上就完成了一个输入关键字并将内容写入json文件的爬虫