理解爬虫原理

本次作业要求来自于:https://edu.cnblogs.com/campus/gzcc/GZCC-16SE1/homework/2881

1. 简单说明爬虫原理

通过程序模拟浏览器请求站点的行为,发送请求,获得响应,对响应的网页代码进行解析提取自己需要的数据,存储到数据库中以供使用。

2. 理解爬虫开发过程

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

用户通过浏览器搜索进行发送请求,服务器把符合的响应传给用户,浏览器获得响应后,对响应的网页代码进行解析渲染呈现内容给用户。

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

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

import requests
url='http://www.gzcc.cn/index.html'
res = requests.get(url)
res.encoding='utf-8'
res.text

运行示例:

 3).了解网页

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

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

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

select(选择器)定位数据

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

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

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

import bs4
from bs4 import BeautifulSoup

html_sample = '''
<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_sample,'html.parser')

print(soups.h1.text)
print(soups.select('a'))
print(soups.select('.link')[0].text)
print(soups.select('#link2')[0].text)

运行示例:

 

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

如url = 'http://news.gzcc.cn/html/2019/xiaoyuanxinwen_0323/11052.html'

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

# 导入requests,获取指定网页的html文件
import requests
url='http://news.gzcc.cn/html/2019/xiaoyuanxinwen_0323/11052.html'
res = requests.get(url)
res.encoding='utf-8'

# 导入bs4中的BeautifulSoup,用来解析网页的html
from bs4 import BeautifulSoup
soupTest=BeautifulSoup(res.text,'html.parser')

# 解析获得对应的内容
title = soupTest.select('.show-title')[0].text

editInfo = soupTest.select('.show-info')[0].text.split()
date = editInfo[0].split(':')[1]
time = editInfo[1]
releaseTime = date + ' ' +time

# 导入datetime类,用于把字符串转换成时间
from datetime import datetime
releaseTime = datetime.strptime(releaseTime,'%Y-%m-%d %H:%M:%S')

author = editInfo[2]
auditor = editInfo[3]
photographer = editInfo[5]
source = editInfo[4]
newsContent = soupTest.select('.show-content')[0].text.strip()

# 解析对应文件获得想要的内容
clickUrl = 'http://oa.gzcc.cn/api.php?op=count&id=11052&modelid=80'
clickStruct = requests.get(clickUrl).text
clickCount = int(clickStruct.split('.html')[-1][2:-3])

# 输出提取的一篇校园新闻的标题、发布时间、发布单位、作者、点击次数、内容等信息
print('校园新闻的标题:',title,'\n发布时间:',releaseTime,'\n',source,'\n',author,'\n',photographer,'\n点击次数:',clickCount)
print('内容主要有:',newsContent)

  运行示例:

 

posted on 2019-03-30 15:31  少年zzy  阅读(108)  评论(0编辑  收藏  举报

导航