理解爬虫原理
作业要求来源:https://edu.cnblogs.com/campus/gzcc/GZCC-16SE1/homework/2881
1. 简单说明爬虫原理
给网站发送请求,获取资源后解析并提取有用数据的程序
2. 理解爬虫开发过程
1).简要说明浏览器工作原理
浏览器工作原理的实质就是实现http协议的通讯,具体过程如下:(HTTP通信的流程,大体分为三个阶段)
1.连接,服务器通过一个ServerSocket类对象对某端口进行监听,监听都之后进行连接,打开一个socket虚拟文件。
2.请求,创建与监理socket连接相关的流对象后,浏览器获取请求,为get请求,则从请求信息中获取所访问的html文件名,向服务器发送请求。
3.响应,服务器收到请求后,搜索相关的目录文件,若不存在,返回错误的信息。若存在,则读取html文件,进行加http头等处理响应给浏览器,浏览器解析html文件,若其中还包含图片,视频等资源,则浏览器再次访问web服务器,获取图片视频等,并对其进行组装显示给用户。
2).使用 requests 库抓取网站数据
requests.get(url) 获取校园新闻首页html代码
代码
url='http://news.gzcc.cn/html/2019/meitishijie_0321/11033.html' res = requests.get(url) res.encoding="UTF-8" print(res.text)
运行结果

3).了解网页
写一个简单的html文件,包含多个标签,类,id
代码
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>test</title> </head> <body> <h1>我的第一个标题</h1> <p>我的第一个段落。</p> </body> </html>
运行结果

4).使用 Beautiful Soup 解析网页
通过BeautifulSoup(html_sample,'html.parser')把上述html文件解析成DOM Tree
select(选择器)定位数据
找出含有特定标签的html元素
找出含有特定类名的html元素
找出含有特定id名的html元素
代码
url='http://news.gzcc.cn/html/2019/meitishijie_0321/11033.html' res = requests.get(url) res.encoding="UTF-8" print(res.text) BSoup = BeautifulSoup(res.text,'html.parser') title = BSoup.select('div .show-title') print(title) content = BSoup.select('div #content') print(content)
运行结果

3.提取一篇校园新闻的标题、发布时间、发布单位、作者、点击次数、内容等信息
如url = 'http://news.gzcc.cn/html/2019/xiaoyuanxinwen_0320/11029.html'
要求发布时间为datetime类型,点击次数为数值型,其它是字符串类型。
代码
from datetime import datetime from bs4 import BeautifulSoup import requests url='http://news.gzcc.cn/html/2019/meitishijie_0321/11033.html' res = requests.get(url) res.encoding="UTF-8" BSoup = BeautifulSoup(res.text,'html.parser') title = BSoup.select('div .show-title')[0].text detail = BSoup.select('div .show-info')[0].text.split('\xa0\xa0') time = BSoup.select('div .show-info')[0].text.split('\xa0\xa0')[0].split(':',1)[1].split("\r") time = time[0].split(" ")[0] + time[0].split(" ")[1] unit = detail[4].split(":")[1] author = detail[2].split(":")[1] time = datetime.strptime(time,'%Y-%m-%d%H:%M:%S') clickurl = "http://oa.gzcc.cn/api.php?op=count&id=11033&modelid=80" count = BeautifulSoup(requests.get(clickurl).text.split(".html")[-1].split("'")[1],'html.parser') content = BSoup.select('div .show-content')[0].text print("标题为:" + title + ",发布时间为:",end="" ) print(time,type(time),end="") print(",发布单位为:" + unit + ",作者为:" + str(author) + ",点击次数为:" + str(count) + "次,内容为:" + content)
运行结果

浙公网安备 33010602011771号