理解爬虫原理

1. 简单说明爬虫原理

爬虫的原理是通过模拟请求的方式去访问相关的开放页面,通过代码的方式去模拟触发网页的点击和跳转,通过流的方式获取到请求响应后的整个html信息,再通过一些工具类去筛选这些信息中包含的有用的信息;

2. 理解爬虫开发过程

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

    游览器通过输入url的请求地址后,获取到web服务器返回的html信息,游览器对这些信息进行解析渲染,最终呈现给用户

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

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

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

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

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

 

soups = BeautifulSoup(html_sample,'html.parser')
a1 =soups.a
a = soups.select('a')
h = soups.select('h1')
t = soups.select('#title')
l = soups.select('.link')

 

 

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

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

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

 

temp=requests.get("http://news.gzcc.cn/html/2019/xiaoyuanxinwen_0329/11095.html")
temp.encoding='utf-8'

soups=BeautifulSoup(temp.text,'html.parser')
title=soups.select('.show-title')[0].text
content_array=soups.select('.show-info')[0].text.split()
content=soups.select('#content')
publish_date=content_array[0].split('发布时间:')[1]

actor=content_array[2]
click=requests.get("http://oa.gzcc.cn/api.php?op=count&id=11095&modelid=80").text.split('.html')[-1].replace("(","").replace(")","").replace("'","").replace(";","")
date=datetime.strptime(publish_date+' '+content_array[1],'%Y-%m-%d %H:%M:%S')

print("标题:"+title)
print("点击次数:"+click)
print(actor)
print(date)
print("内容:"+content[0].text)

 

 

 

 

 

posted on 2019-03-29 21:56  liliguang  阅读(259)  评论(0编辑  收藏  举报