理解爬虫原理


1. 简单说明爬虫原理

爬虫的原理是通过模拟请求的方式去访问相关的开放页面,通过代码的方式去模拟触发网页的点击和跳转,通过流的方式获取到请求响应后的整个html信息,

再通过一些工具类去筛选这些信息中包含的有用的信息;

2. 理解爬虫开发过程

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

  游览器通过输入url的请求地址后,获取到web服务器返回的html信息,游览器对这些信息进行解析渲染,最终呈现给用户

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 > 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
import requests

url='http://www.gzcc.cn/'
html=requests.get(url=url)
html.encoding='utf-8'
order=BeautifulSoup(html.text,'lxml')
order1=order.select('a')
order2=order.select('.gray')
order3=order.select('#img1')

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

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

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

temp=requests.get("http://news.gzcc.cn/html/2019/xiaoyuanxinwen_0329/11095.html")
temp.encoding='utf-8'

soups=BeautifulSoup(temp.text,'html.parser')
title=soups.select('.show-title')[0].text
content_array=soups.select('.show-info')[0].text.split()
content=soups.select('#content')
publish_date=content_array[0].split('发布时间:')[1]

actor=content_array[2]
click=requests.get("http://oa.gzcc.cn/api.php?op=count&id=11095&modelid=80").text.split('.html')[-1].replace("(","").replace(")","").replace("'","").replace(";","")
date=datetime.strptime(publish_date+' '+content_array[1],'%Y-%m-%d %H:%M:%S')
#获取发布时间
retime = retime.lstrip('发布时间:')
#发布时间转换成datetime类型
retime = datetime.strptime(retime,'%Y-%m-%d %H:%M:%S')
#获取新闻作者
author = info[2].split(':')[1]
#获取审核
examine = info[3].split(':')[1]
#获取新闻来源
source = info[4].split(':')[1]
#获取点击次数,转换点击次数为int类型
print('标题:',title,'
发布时间:',date,'
审核:',examine,'
新闻来源:',source,'
点击次数:',click,'
内容:',content[0].text)
理解爬虫原理