作业来源:https://edu.cnblogs.com/campus/gzcc/GZCC-16SE1/homework/2881

 

1. 简单说明爬虫原理

  通过访问请求爬取网页上的数据

2. 理解爬虫开发过程

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

  URL解析/DNS解析查找域名IP地址,网络连接发起HTTP请求,HTTP报文传输过程,服务器接收数据,服务器响应请求/MVC,服务器返回数据,客户端接收数据,浏览器加载/渲染页面,打印绘制输出所看到的网页。

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

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

SYurl='http://news.gzcc.cn/'
SYres = requests.get(SYurl)
SYres.text

 

3).了解网页

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

<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元素

soups = BeautifulSoup(html_sample,'html.parser')
a = soups.select('a')
a

 

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

l = soups.select('.link')
l

 

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

t = soups.select('#title')
t

 

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

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

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

import requests
import bs4
from bs4 import BeautifulSoup
url='http://news.gzcc.cn/html/2019/xiaoyuanxinwen_0328/11080.html'
res = requests.get(url)
res.encoding = 'utf-8'
soupn = BeautifulSoup(res.text,'html.parser')

标题:

biaoti = soupn.select('.show-title')[0].text

 

发布时间:

times = soupn.select('.show-info')[0].text.split()[0].split(':')[1]
times = times +' '+ soupn.select('.show-info')[0].text.split()[1]
times = times.replace('-', ' ').replace(':', ' ').lower().split()
dt = datetime(int(times[0]),int(times[1]),int(times[2]),int(times[3]),int(times[4]),int(times[5]))

 

发布单位:

where = soupn.select('.show-info')[0].text.split('\xa0\xa0')[4].split('')[1]
where

 

作者:

witer = soupn.select('.show-info')[0].text.split()[2].split('')[1]
witer

 

点击次数:

cilckUrl='http://oa.gzcc.cn/api.php?op=count&id=11080&modelid=80'
cilckRes = requests.get(cilckUrl)
cilckTimes = int(cilckRes.text.split('.html')[-1].split("'")[1])
cilckTimes

 

 内容:

texts = soupn.select('.show-content')[0].text
texts = texts.replace('\n', '').replace('\r', '').replace('\u3000', '').lower()
texts

 

posted on 2019-03-29 17:46  浅锘晗  阅读(118)  评论(0编辑  收藏  举报