天天看點

了解爬蟲原理

作業要求源于:https://edu.cnblogs.com/campus/gzcc/GZCC-16SE1/homework/2881

1. 簡單說明爬蟲原理

網際網路就像一張大的蜘蛛網,資料便是存放在蜘蛛網的各個節點,爬蟲就像一隻蜘蛛,沿着網絡抓去自己需要的資料。爬蟲:向網站發起請求,擷取資源後進行分析并提取有用的資料的程式

2. 了解爬蟲開發過程

  1).簡要說明浏覽器工作原理

    在浏覽器的位址欄輸入網址并按回車後,浏覽器就會向伺服器發送http請求,伺服器接收到請求後進行業務處理并向浏覽器傳回請求的資源,浏覽器将擷取到的傳回資料進行解析、渲染,形成網頁。

  2).使用 requests 庫抓取網站資料

    requests.get(url) 擷取校園新聞首頁html代碼

import requests
import bs4
from bs4 import BeautifulSoup
url = "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 = ' \
<html> \
    <body> \
          <h1 id="title">Hello</h1> \
          <a href="# link1" class="link" id="link1"> This is link1</a>\
          <a href="# link2" class="link" id="link2"> 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="# link1" class="link" id="link1"> 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                                       # 擷取文檔中的第一個與‘a’同名的标簽,傳回類型為Tag
h1 = soups.select('h1')                           # 擷取标簽名為‘h1’的标簽的内容,傳回類型為list
link_class = soups.select('.link')                # 擷取類名為‘link’的标簽的内容,傳回類型為list
link_id = soups.select('#link2')                  # 擷取id為‘link2’的标簽的内容,傳回類型為list
print(a)
print(h1)
print(link_class)
print(link_id)      
了解爬蟲原理

3.提取一篇校園新聞的标題、釋出時間、釋出機關、作者、點選次數、内容等資訊

  提取的校園新聞url = 'http://news.gzcc.cn/html/2019/xiaoyuanxinwen_0329/11095.html'

  釋出時間為datetime類型,點選次數為數值型,其它是字元串類型。

代碼:

import requests
import bs4
from bs4 import BeautifulSoup
url = "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 + ' '+ xinTime
print(newdt)
from datetime import datetime
now = 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)      
了解爬蟲原理
了解爬蟲原理