天天看點

了解爬蟲原理

1.簡單說明爬蟲原理

爬蟲就是通過網際網路各個沾點組成的節點網,通過代碼傳回給浏覽器,然後解析這部分的代内容,将網頁内的内容簡潔地呈現在我們的面前。爬蟲的流程可以分為:發送請求、擷取響應内容、解析内容、儲存資料。

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

import requests
from bs4 import BeautifulSoup
url='http://site.gzcc.cn/html/2018/xkcg_0615/1729.html'
res = requests.get(url)
res.encoding = 'utf-8'
res.text      
了解爬蟲原理

3.了解網頁

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

<html>
  <head>
    <h1 id="title">簡單視訊網頁</h1>
  </head>
  <body>
    <div>
      <p1>騰訊視訊網頁<p1><br>
      <a href="https://v.qq.com/?ptag=qqbsc" >騰訊視訊</a>
    </div>
  </body>
</html>      

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

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

select(選擇器)定位資料

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

import requests
from bs4 import BeautifulSoup
url='http://site.gzcc.cn/html/2018/xkcg_0615/1729.html'
res = requests.get(url)
res.encoding = 'utf-8'
res.text

yuansu = soup.select('li')
yuansu      
了解爬蟲原理

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

tedinglei = soup.select('.news-list-title')
tedinglei      
了解爬蟲原理

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

id = soup.select('#q')
id      
了解爬蟲原理

3.提取一篇校園新聞的标題、釋出時間、釋出機關

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

import requests
from bs4 import BeautifulSoup

url="http://news.gzcc.cn/html/2019/xiaoyuanxinwen_0320/11029.html";
res=requests.get(url);
res.encoding=res.apparent_encoding;
text=res.text;

soup=BeautifulSoup(text,"html.parser");

title=soup.select(".show-title");
print(title);

time=soup.select(".show-info");
print(time);      
了解爬蟲原理