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

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

这次作业的要求来源:https://edu.cnblogs.com/campus/gzcc/GZCC-16SE1/homework/2881

1. 简单说明爬虫原理

通过代码从网页抓取所需的信息

2. 理解爬虫开发过程

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

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

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

#导入requests库import requestsfrom bs4 import BeautifulSoupurl = 'http://news.gzcc.cn/html/2019/xiaoyuanxinwen_0331/11111.html'news = requests.get(url)news.encoding = 'utf-8'print(news.text)

  

3).了解网页

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

			
1
用户名:
密 码:
表单外的文本框:

  

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

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

select(选择器)定位数据

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

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

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

 

import requestsfrom bs4 import BeautifulSoupurl = 'http://news.gzcc.cn/html/2019/xiaoyuanxinwen_0331/11111.html'news = requests.get(url)news.encoding = 'utf-8'newSoup = BeautifulSoup(news.text,'html.parser')#找出含有特定标签的html元素newSpan = newSoup.select('span');print('找出含有span标签的html元素:')print(newSpan);#找出含有特定类名的html元素newInfo = newSoup.select('.show-info');print('找出class=show-info的html元素:');print(newInfo);#找出含有特定id名的html元素newContent = newSoup.select('#content')[0].text;print('找出id=content的html元素:');print(newContent);

 

  

 

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

如url = ''

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

 

import requestsfrom bs4 import BeautifulSoupurl = 'http://news.gzcc.cn/html/2019/xiaoyuanxinwen_0331/11111.html'news = requests.get(url)news.encoding = 'utf-8'newSoup = BeautifulSoup(news.text,'html.parser')#标题title = newSoup.select('.show-title')[0].textprint('标题:'+title);#发布时间newDate = newSoup.select('.show-info')[0].text.split()[0].lstrip('发布时间:')newTime = newSoup.select('.show-info')[0].text.split()[1]newDateTime = newDate+' '+newTimeprint('发布时间:'+newDateTime);#发布单位source = newSoup.select('.show-info')[0].text.split()[4].lstrip('来源:')print('发布单位:'+source);

  

 

转载于:https://www.cnblogs.com/liangqiuhua/p/10635919.html

你可能感兴趣的文章
sort-快速排序
查看>>
Treeview SelectedNodeChanged event not firing
查看>>
mysql 日志管理
查看>>
VMware WorkStation安装时提示The MSI failed
查看>>
JavaScript, AJAX树形控件大全(all kinds of TreeView Controls by JavaScript, AJAX)[转载]
查看>>
[转]MSDTC on server '''' is unavailable. 的解决办法
查看>>
SpringMVC注解
查看>>
Spring 依赖注入
查看>>
数据结构——二叉树树的遍历理论与实现
查看>>
delphi AfterScrol
查看>>
软件外包,IT咨询和转型
查看>>
[MySQL] InnoDB三大特性之 - 插入缓冲
查看>>
Sphinx安装配置应用
查看>>
dns 域名解析
查看>>
nohup top & 问题: top: failed tty get
查看>>
详解ORACLE数据库的分区表
查看>>
Windows7下安装SQLServer2005过程详解
查看>>
reids基于订阅的聊天室
查看>>
[转载]php中的ssh2
查看>>
Centos发布java的war包后,无法访问发布的工程
查看>>