理解爬虫原理

2. 理解爬虫开发过程

1).简要说明浏览器工作原理;

 Web浏览器提交请求后,通过HTTP协议传送给Web服务器。Web服务器接到后, 进行事务处理,处理结果又通过HTTP传回给Web浏览器,从而在Web浏览器上显示出所请求的页面。 

 

2).使用 requests 库抓取网站数据;

requests.get(url) 获取校园新闻首页html代码

import requests
res=requests.get('http://news.gzcc.cn/html/2019/xiaoyuanxinwen_0328/11080.html')
res.encoding = 'utf-8'

 

3).了解网页

写一个简单的html文件,包含多个标签,类,id

html = ' \
<html> \
<body> \
<h1 id="title">Hello</h1> \
<a href="#" class="link"> This is link1</a>\
<a href="# link2" class="link" qao=123> This is link2</a>\
</body> \
</html> '

 

4).使用 Beautiful Soup 解析网页;

通过BeautifulSoup(html_sample,'html.parser')把上述html文件解析成DOM Tree

select(选择器)定位数据

找出含有特定标签的html元素

找出含有特定类名的html元素

找出含有特定id名的html元素

from bs4 import BeautifulSoup
html = ' \
<html> \
    <body> \
          <h1 id="title">Hello</h1> \
          <a href="#" class="link"> This is link1</a>\
          <a href="# link2" class="link" id="link2"> This is link2</a>\
    </body> \
</html> '
soups=BeautifulSoup(html,'html.parser')
a=soups.a
h=soups.select('h1')
l=soups.select('.link')
i=soups.select('#link2')
print(soups)
print(i)

 

运行截图:

 

3.提取一篇校园新闻的标题、发布时间、发布单位、作者、点击次数、内容等信息

如url = 'http://news.gzcc.cn/html/2019/xiaoyuanxinwen_0320/11029.html'

要求发布时间为datetime类型,点击次数为数值型,其它是字符串类型。

 

import requests
from bs4 import BeautifulSoup
from datetime import datetime

url="http://news.gzcc.cn/html/2019/xiaoyuanxinwen_0323/11052.html"
res=requests.get(url)
res.encoding='utf-8'
soup=BeautifulSoup(res.text,'html.parser')#使用指定解析器解析获得res文本


title=soup.select('.show-title')[0].text
context=soup.select('#content')[0].text.strip()
clickUrl="http://oa.gzcc.cn/api.php?op=count&id=11052&modelid=80"
click=requests.get(clickUrl).text.split('.html')[-1][2:-3]
author=soup.select('.show-info')[0].text.split()[2]
post=soup.select('.show-info')[0].text.split()[4]
time=soup.select('.show-info')[0].text.split()[0:2]
time=' '.join(time)
print("标题:{}".format(title)) print(time) print(author) print(post) print("点击次数:{}".format(click)) print("内容:{}".format(context))
#times=time.strftime('%Y{y}%m{m}%d{d} %H{h}%M{f}%S{s}').format(y='年',m='月',d='日',h='时',f='分',s='秒')

 

运行截图:

 

posted @ 2019-03-29 20:50  陈泽诚  阅读(155)  评论(0编辑  收藏  举报