博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
理解爬虫原理
阅读量:7305 次
发布时间:2019-06-30

本文共 2393 字,大约阅读时间需要 7 分钟。

作业要求源于:

1. 简单说明爬虫原理

互联网就像一张大的蜘蛛网,数据便是存放在蜘蛛网的各个节点,爬虫就像一只蜘蛛,沿着网络抓去自己需要的数据。爬虫:向网站发起请求,获取资源后进行分析并提取有用的数据的程序

2. 理解爬虫开发过程

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

    在浏览器的地址栏输入网址并按回车后,浏览器就会向服务器发送http请求,服务器接收到请求后进行业务处理并向浏览器返回请求的资源,浏览器将获取到的返回数据进行解析、渲染,形成网页。

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

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

import requestsimport bs4from bs4 import BeautifulSoupurl = "http://news.gzcc.cn/html/2019/xiaoyuanxinwen_0329/11095.html"res = requests.get(url)res.encoding = 'utf-8'soupn = BeautifulSoup(res.text,'html.parser')print(soupn)

  3).了解网页

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

html = ' \ \     \          

Hello

\ This is link1\ This is link2\ \ '

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

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

    select(选择器)定位数据

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

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

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

from bs4 import BeautifulSouphtml = ' \ \     \          

Hello

\ This is link1\ This is link2\ \ 'soups = BeautifulSoup(html, 'html.parser')a = soups.a # 获取文档中的第一个与‘a’同名的标签,返回类型为Tagh1 = soups.select('h1') # 获取标签名为‘h1’的标签的内容,返回类型为listlink_class = soups.select('.link') # 获取类名为‘link’的标签的内容,返回类型为listlink_id = soups.select('#link2') # 获取id为‘link2’的标签的内容,返回类型为listprint(a)print(h1)print(link_class)print(link_id)

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

  提取的校园新闻url = '

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

代码:

import requestsimport bs4from bs4 import BeautifulSoupurl = "http://news.gzcc.cn/html/2019/xiaoyuanxinwen_0329/11095.html"res = requests.get(url)res.encoding = 'utf-8'soupn = BeautifulSoup(res.text,'html.parser')print("内容:"+soupn.select('.show-content')[0].text)print(soupn.title)#print(soupn.select(".show-info")[0].text.split(':')[1])info = soupn.select(".show-info")[0].text.split()#print(info)xinDate = info[0].split(':')[1]print(xinDate)xinTime = info[1]print(xinTime)newdt = xinDate + ' '+ xinTimeprint(newdt)from datetime import datetimenow = datetime.now()#now = now.strptime('%Y{y}%m{m}%d{d} %H{h}%M{f}%S{s}').__format__(y='年',m='月',d='日',h='时',f='分',s='秒')now = now.strftime('%Y{y}%m{m}%d{d} %H{h}%M{f}%S{s}').format(y='年',m='月',d='日',h='时',f='分',s='秒')print(now)clickurl = "http://oa.gzcc.cn/api.php?op=count&id=11095&modelid=80"click = requests.get(clickurl).text.split("'")[3]print(click)

 

转载于:https://www.cnblogs.com/lc97/p/10638642.html

你可能感兴趣的文章
AngularJS 模态对话框
查看>>
Camera HAL v3 overview
查看>>
存储过程
查看>>
HDU 5701 中位数计数 暴力
查看>>
集群搭建系列
查看>>
CVBS视频信号解析
查看>>
[javaSE] 数据结构(队列)
查看>>
poj1753-Flip Game 【状态压缩+bfs】
查看>>
基于MINA框架快速开发网络应用程序
查看>>
SVN的学习和安装
查看>>
MySQL 5.7 深度解析: 临时表空间
查看>>
lamp一键安装
查看>>
Android 坐标系和 MotionEvent 分析、滑动
查看>>
PowerBI 引入时间智能
查看>>
mybatis.generator.configurationFile
查看>>
GDB 调试 PHP文件
查看>>
C# 之 Structure 和 Class的区别
查看>>
angular语法:Controller As
查看>>
JUC回顾之-ConcurrentHashMap源码解读及原理理解
查看>>
Linux 利器- Python 脚本编程入门(一)
查看>>