近期爬蟲學習小彙總
阿新 • • 發佈:2020-07-25
近期爬蟲學習小彙總
爬蟲理論
什麼是爬蟲:
通過編寫程式,模擬瀏覽器上網,然後讓其去網際網路上抓取資料的過程。
爬蟲究竟是合法還是違法的?
在法律中是不被禁止
具有違法風險
善意爬蟲 惡意爬蟲
爬蟲帶來的風險可以體現在如下2方面:
爬蟲干擾了被訪問網站的正常運營
爬蟲抓取了收到法律保護的特定型別的資料或資訊
http協議
概念:伺服器和客戶端進行資料互動的一種形式
User-Agent:請求載體的身份表示
Connection:請求完畢後,是斷開的連線還是保持連線
常用響應頭資訊
Content-Type:伺服器響應回客戶端的資料型別
https協議:
- 安全的超文字傳輸協議
加密方式
- 對稱祕鑰加密
- 非對稱祕鑰加密
- 證書祕鑰加密
爬蟲思路
分析網頁,確定 url 路徑
發起request請求,獲取相應資料
資料解析篩選
儲存資料
requests庫:模擬瀏覽器傳送請求
import requests url="http://www.dianping.com" #協議地址 header={ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36" } res=requests.get(url,headers=header,timeout=2) #超時引數為2秒 res.encoding # 檢視編碼 res.status_code #狀態資訊,200正常,404是錯誤 res.apparent_encoding #分析內容可能的編碼 #把響應的二進位制位元組流轉化為str型別 res.content.decode() #括號裡可以寫gbk,獲取網頁原始碼 第二個嘗試方式
- text 文字資料
- json 物件資料
- content 二進位制資料(一般用於圖片)
通用程式碼框架
def getHTMLText(url): header={ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36" } try: r=requests.get(url,timeout=30,headers=header) r.raise_for_status #如果狀態不為200,引發HTTPError異常 r.encoding=r.apparent_encoding return r.text except: return "產生異常"
傳參
import requests
keyword="python"
try:
kv={"q":keyword}
r=requests.get("http://www.so.com",params=kv) # 搜尋引擎後面的引數 ,表示搜尋的內容
print(r.request.url)
r.raise_for_status() # 返回值 <bound method Response.raise_for_status of <Response [200]>>
print(len(r.text))
except:
print(r.status_code)
print("爬取失敗")
xpath:
例項化一個etree的物件,需要將被解析的頁面載入到該物件中,返回的是一個列表,但是索引是從一開始的
語法:
/: 表示的是從根節點開始定位,表示的是一個層級
//: 表示的是多個層級,可以表示從任意位置開始定位
屬性定位://div[@class="song"]
/text() 獲取標籤中直系文字
//text() 獲取所有文字
/@attrName取屬性
使用案例
from lxml import etree
import requests
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36"}
url="http://sc.chinaz.com/tubiao/dongmankatong_2.html"
page_text=requests.get(url,headers)
page_text.encoding="utf8"
page_text=page_text.text
tree=etree.HTML(page_text)
ico_list=tree.xpath('.//div[@class="text_left"]/ul/li/p/a/@href')
beautifulsoup:用於捕獲標籤
案例演示與講解
from bs4 import BeautifulSoup
import requests
demo="http://python123.io/ws/demo.html"
demo=requests.get(demo)
demo=demo.text #使用requests庫獲取文字
soup=BeautifulSoup(demo,"html.parser")
soup.title # title標籤和裡面的內容 <title>This is a python demo page</title>
soup.a #獲取a標籤 <a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a>
soup.a.name # a標籤的名字
soup.a.parent.parent.name #獲取父標籤的名字
soup.a.attrs # a標籤的屬性 以字典形式b返回
soup.a.attrs["class"] # 獲取class屬性
soup.b.string #b標籤中非屬性字串,即直系內容,如果沒有,那就是沒有
soup.head.contents #將子標籤存入列表 <head><title>This is a python demo page</title></head>
soup.a.next_sibling # 返回HTML文字順序下一個平行節點標籤
soup.prettify() # 基於html的輸出 將每個標籤用換行符表示出來
soup.find("a") #只找出一個,a標籤
soup.find_all("a") #只找出所有a標籤
soup.find_all(id="link1") # 找所以含有id="link1"的標籤
圖片與檔案爬取
圖片和檔案還有音訊都是二進位制檔案,需要找到檔案源頭,發起響應,然後寫入本地即可
案例演示
import requests
import os
url="http://pic.netbian.com/uploads/allimg/190917/151703-1568704623b3da.jpg"
root=r"C:\Users\32198\Pictures\爬蟲圖片"
path=root+"/"+url.split("/")[-1]
try:
if not os.path.exists(root):
os.mkdir(root)
if not os.path.exists(path):
r=requests.get(url)
with open (path,"wb") as f:
f.write(r.content)
f.close
print("儲存檔案成功")
else:
print("檔案已存在")
except:
print("包存失敗")