使用Python開發(fā)的同學一定聽說過Requsts庫,它是一個用于發(fā)送HTTP請求的測試。如比我們用Python做基于HTTP協(xié)議的接口測試,那么一定會首選Requsts,因為它即簡單又強大。現(xiàn)在作者Kenneth Reitz 又開發(fā)了requests-html 用于做爬蟲。
該項目從3月上線到現(xiàn)在已經7K+的star了!
GiHub項目地址:
https://github.com/kennethreitz/requests-html
requests-html 是基于現(xiàn)有的框架 PyQuery、Requests、lxml、beautifulsoup4等庫進行了二次封裝,作者將Requests設計的簡單強大的優(yōu)點帶到了該項目中。
#安裝:
> pip install requests-html
教程與使用:
使用GET請求 https:// 網站。
### ~~~~~~~~~~拜師學藝~~~~~~~~~~
先來看看requests的基本使用。
from requests_html import HTMLSession
session = HTMLSession()
r = session.get('https:///')
# 獲取頁面上的所有鏈接。
all_links = r.html.links
print(all_links)
# 獲取頁面上的所有鏈接,以絕對路徑的方式。
all_absolute_links = r.html.absolute_links
print(all_absolute_links)
### ~~~~~~~~~~小試牛刀~~~~~~~~~~
作為一個IT技術人員,是不是要時時關心一下科技圈的新聞,上博客園新聞頻道,抓取最新的推薦新聞。
from requests_html import HTMLSession
session = HTMLSession()
r = session.get("https://news.cnblogs.com/n/recommend")
# 通過CSS找到新聞標簽
news = r.html.find('h2.news_entry > a')
for new in news:
print(new.text) # 獲得新聞標題
print(new.absolute_links) # 獲得新聞鏈接
執(zhí)行結果:
雷軍:小米硬件綜合凈利率永遠不超5%!
{'https://news.cnblogs.com/n/595156/'}
苦大仇深的“中國芯”,不妨學一學有趣的樹莓派
{'https://news.cnblogs.com/n/595143/'}
我的快遞,憑什么不能給我送到家!
{'https://news.cnblogs.com/n/595087/'}
倪光南回應方舟CPU失敗論:企業(yè)失敗不等于技術失敗
{'https://news.cnblogs.com/n/595102/'}
清華大學突破紀錄:首次實現(xiàn)25個量子接口間量子糾纏
{'https://news.cnblogs.com/n/595103/'}
定向免流量套餐用著爽,但背后的“坑”你可能不知道
{'https://news.cnblogs.com/n/595061/'}
你在微信群侃大山,有人卻用微信群發(fā)大財
{'https://news.cnblogs.com/n/595059/'}
馬云的三觀
{'https://news.cnblogs.com/n/595047/'}
美國科技強大的全部秘密
{'https://news.cnblogs.com/n/595043/'}
蓋茨看著聽證會上的扎克伯格:滿眼都是20年前的自己
{'https://news.cnblogs.com/n/595025/'}
史上最清晰癌細胞轉移3D影像來襲
{'https://news.cnblogs.com/n/595019/'}
中興員工:華為僅部分芯片自己設計 誰被美制裁都得死
{'https://news.cnblogs.com/n/594967/'}
作為曾經的華為員工,我想替中興公司說兩句公道話
{'https://news.cnblogs.com/n/594962/'}
匿名網友回評梁寧:方舟bug無數(shù) 貼錢給別人都未必用
{'https://news.cnblogs.com/n/594932/'}
一段關于國產芯片和操作系統(tǒng)的往事
{'https://news.cnblogs.com/n/594900/'}
芯片股總市值低于美國巨頭 有公司靠政府補助盈利
{'https://news.cnblogs.com/n/594902/'}
被自家律師送上“槍口”的“二流”中興
{'https://news.cnblogs.com/n/594859/'}
Google正在失去DeepMind?
{'https://news.cnblogs.com/n/594853/'}
擴展:我們可以進一步將這里數(shù)據(jù)做持久化處理,設計出自己的“頭條”。
### ~~~~~~~~~~小有成就~~~~~~~~~~
接下來我們到網站上下載壁紙,以美桌網(www.)為例。
from requests_html import HTMLSession
import requests
# 保存圖片到bg/目錄
def save_image(url, title):
img_response = requests.get(url)
with open('./bg/'+title+'.jpg', 'wb') as file:
file.write(img_response.content)
# 背景圖片地址,這里選擇1920*1080的背景圖片
url = "http://www./wallpaper_2358_0_10_1.html"
session = HTMLSession()
r = session.get(url)
# 查找頁面中背景圖,找到鏈接,訪問查看大圖,并獲取大圖地址
items_img = r.html.find('ul.clearfix > li > a')
for img in items_img:
img_url = img.attrs['href']
if "/wallpaper_detail" in img_url:
r = session.get(img_url)
item_img = r.html.find('img.pic-large', first=True)
url = item_img.attrs['src']
title = item_img.attrs['title']
print(url+title)
save_image(url, title)
這個網站上的圖片還是很容易獲取的,在上面的代碼塊中我加了注釋。這里不再說明。

|