理解爬虫原理

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

1. 简单说明爬虫原理

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

2. 理解爬虫开发过程

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

      就是将用户选择的web资源呈现出来,它需要从服务器请求资源,并将其展示在浏览器窗口中,资源格式通常是HTML,也包括PDFIMAGES等。

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

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

import requests
url="http://news.gzcc.cn/html/2019/xiaoyuanxinwen_0329/11104.html"
res=requests.get(url)
res.encoding='UTF-8'

   3).了解网页

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

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<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元素

from bs4 import BeautifulSoup
html = ' 
<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,'html.parser')
a = soups.a
h = soups.select('h1')
l = soups.select('.link')
lid = soups.select('#link2')
print(soups)
print(lid)

 

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

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

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

代码:

import requests
from bs4 import BeautifulSoup
from datetime import datetime
url="http://news.gzcc.cn/html/2019/xiaoyuanxinwen_0329/11104.html"
res=requests.get(url)
res.encoding='UTF-8'
soup=BeautifulSoup(res.text,'html.parser')
#发布时间
time=soup.select('.show-info')[0].text.split()[0].split(':')[1]
time1=soup.select('.show-info')[0].text.split()[1]
newtime=time+' '+time1
newtime=datetime.strptime(newtime,"%Y-%m-%d %H:%M:%S")
print("发布时间:"+str(newtime))
#作者
author=soup.select('.show-info')[0].text.split()[2]
print(author)
#审核
check=soup.select('.show-info')[0].text.split()[3]
print(check)
#来源
come=soup.select('.show-info')[0].text.split()[4]
print(come)
#点击次数
clickUrl="http://oa.gzcc.cn/api.php?op=count&id=11086&modelid=80"
clickNum = requests.get(clickUrl).text.split(';')[3]
c =int(clickNum.split("'")[3])
print('点击次数:{}次'.format(c))
#正文内容
print("正文内容:" + soup.select('.show-content')[0].text)

运行结果:

 

原文地址:https://www.cnblogs.com/wytai/p/10638904.html