菜鸟学IT之python网页爬取初体验

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

1. 简单说明爬虫原理

 爬虫简单来说就是通过程序模拟浏览器放松请求站点的行为,把站点返回的HTML代码/JSON数据/二进制数据(图片、视频) 爬到本地,通过一些算法进而提取自己需要的数据,存放起来使用。

2. 理解爬虫开发过程

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

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

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

import requests
url = 'http://news.gzcc.cn/html/2019/xiaoyuanxinwen_0320/11029.html'
res = requests.get(url)
type(res)
res.encoding ='utf-8'
soupn = BeautifulSoup(res.text,'html.parser')  # html 规格打印
print(soupn)

截图:

3).了解网页

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

html_sample = ' 
<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> '
# 各种查询方式
a = soupn.select('a') # 使用标签节点a查询
ids = soupn.select('#id') # 使用id号查询
classs = soupn.select('.class') # 使用class类查询
print(a,ids,classs)

  

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

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

select(选择器)定位数据

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

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

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

idchaxun = soupn.select('#content')[0].text
biaoqianchaxun = soupn.select('img')[0]['src']
leichaxun = soupn.select('.show-info')[0].text
print(idchaxun,biaoqianchaxun,leichaxun)

 截图:

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

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

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

下载:requests、BeautifulSoup4库

获取网页游览次数请求的url:

clickUrl='http://oa.gzcc.cn/api.php?op=count&id=11029&modelid=80'
b = requests.get(clickUrl).text
b2 = requests.get(clickUrl).text.split('.html')[-1]
print(b2)

 完整代码:

from datetime import datetime

import requests
from bs4 import BeautifulSoup
url = 'http://news.gzcc.cn/html/2019/xiaoyuanxinwen_0320/11029.html'
res = requests.get(url)
type(res)
res.encoding = 'utf-8'
soupn = BeautifulSoup(res.text,'html.parser')  # html 规格打印

q = soupn.title.text  # 标题
soupn1 = soupn.select('.show-info')[0].text  # 作者与发布时间等信息

# 时间转化为datetime类型
time1 = soupn.select('.show-info')[0].text.split()[0].split(':')[1]
time2 = soupn.select('.show-info')[0].text.split()[1]
Time = time1 + ' ' + time2
Time1 = datetime.strptime(Time, '%Y-%m-%d %H:%M:%S')
Time2 = datetime.strftime(Time1, '%Y{y}-%m{m}-%d{d} %H{H}%M{M}%S{S}').format(y='', m='', d='', H='', M='', S='')

Zuozhe = soupn.select('.show-info')[0].text.split()[2]  # 作者
shenhe = soupn.select('.show-info')[0].text.split()[3]  # 审核
laiyuan = soupn.select('.show-info')[0].text.split()[4]   # 来源


# 游览次数
clickUrl='http://oa.gzcc.cn/api.php?op=count&id=11029&modelid=80'
b = requests.get(clickUrl).text.split('.html')[-1]  # 获取总游览次数
sel = "();''"
for i in sel:
    b = b.replace(i, '')

zhengwen = soupn.select('.show-content')[0].text

print("
"+"标题:"+q+"
"+"发布时间:"+Time2+"
"+
      Zuozhe+"
"+shenhe+"
"+laiyuan+"
"+
      "游览次数:"+b+"
"+"正文:"+zhengwen)

效果截图:

原文地址:https://www.cnblogs.com/JGaoLin/p/10622907.html