天天看點

了解爬蟲原理

作業來自:https://edu.cnblogs.com/campus/gzcc/GZCC-16SE1/homework/2881

1. 簡單說明爬蟲原理

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

2. 了解爬蟲開發過程

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

  在浏覽器輸入内容,浏覽器會将請求發送到伺服器,伺服器響應後傳回響應結果給浏覽器,然後根據響應向使用者顯示相關内容。

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

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

3).了解網頁

寫一個簡單的html檔案,包含多個标簽,類,id

4).使用 Beautiful Soup 解析網頁;

通過BeautifulSoup(html_sample,'html.parser')把上述html檔案解析成DOM Tree

select(選擇器)定位資料

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

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

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

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

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

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

 代碼:

import requests
import bs4
from bs4 import BeautifulSoup as bs
from datetime import datetime

def html(url):
    response=requests.get(url=url)
    response.encoding='utf-8'
    soup=bs(response.text,'html.parser')
    return soup

url="http://news.gzcc.cn/html/2019/xiaoyuanxinwen_0328/11080.html"
url2='http://oa.gzcc.cn/api.php?op=count&id=11080&modelid=80'

#标題
title=html(url).select('div .show-title')[0].text
print("新聞标題:"+title)
#時間
time1=html(url).select('div .show-info')[0].text.split()[0].split(':')[1]
time2=html(url).select('div .show-info')[0].text.split()[1]
Time=time1+ ' ' +time2
print("釋出時間:"+Time)
#釋出機關
comFrom=html(url).select('div .show-info')[0].text.split()[4].split(':')[1]
print("釋出機關:"+comFrom)
#作者
write=html(url).select('div .show-info')[0].text.split()[2].split(':')[1]
print("作者:"+write)
#點選次數
count=html(url2).text.split()[0].split('html')[-1]
ss="()';"
for i in ss:
    count=count.replace(i,'')
co=int(count)
print("點選次數:",co)
#内容
cont=html(url).select('div .show-content')[0].text.replace('。','\n')
print("新聞内容:")
print(cont)

#字元串轉化為Data類型
now=datetime.strptime(Time,'%Y-%m-%d %H:%M:%S')
print(type(now))
#Data轉化字元串
now1=datetime.now()
now1=datetime.strftime(now1,'%Y{y}-%m{m}-%d{d} %H{H}:%M{M}:%S{S}').format(y='年',m='月',d='日',H='時',M='分',S='秒')
print(now1)      

運作結果: