1. 程式人生 > >Python 爬蟲實戰(二):使用 requests-html

Python 爬蟲實戰(二):使用 requests-html

分享 -html 調用 交流 html 技術 python-re find 自己的

Python 爬蟲實戰(一):使用 requests 和 BeautifulSoup,我們使用了 requests 做網絡請求,拿到網頁數據再用 BeautifulSoup 解析,就在前不久,requests 作者 kennethreitz 出了一個新庫 requests-html,Pythonic HTML Parsing for Humans?,它可以用於解析 HTML 文檔的。requests-html 是基於現有的框架 PyQuery、Requests、lxml 等庫進行了二次封裝,更加方便開發者調用。

安裝

Mac:

pip3 install requests-html

Windows:

pip install requests-html

實例

技術分享圖片

代碼擼多了,讓我們看會妹紙,爬的網站我選的是 http://www.win4000.com/zt/xinggan.html ,打開網站,觀察到這是個列表,圖片是縮略圖,要想保存圖片到本地,當然需要高清大圖,因此得進入列表詳情,進一步解析,完整代碼如下:

from requests_html import HTMLSession
import requests
import time

session = HTMLSession()


# 解析圖片列表
def get_girl_list():
    # 返回一個 response 對象
    response =
session.get('http://www.win4000.com/zt/xinggan.html') # 單位秒數 content = response.html.find('div.Left_bar', first=True) li_list = content.find('li') for li in li_list: url = li.find('a', first=True).attrs['href'] get_girl_detail(url) # 解析圖片詳細
def get_girl_detail(url): # 返回一個 response 對象 response = session.get(url) # 單位秒數 content = response.html.find('div.scroll-img-cont', first=True) li_list = content.find('li') for li in li_list: img_url = li.find('img', first=True).attrs['data-original'] img_url = img_url[0:img_url.find('_')] + '.jpg' print(img_url + '.jpg') save_image(img_url) # 保持大圖 def save_image(img_url): img_response = requests.get(img_url) t = int(round(time.time() * 1000)) # 毫秒級時間戳 f = open('/Users/wuxiaolong/Desktop/Girl/%d.jpg' % t, 'ab') # 存儲圖片,多媒體文件需要參數b(二進制文件) f.write(img_response.content) # 多媒體存儲content f.close() if __name__ == '__main__': get_girl_list()

代碼就這麽多,是不是感覺很簡單啊。

說明:

1、requests-html 與 BeautifulSoup 不同,可以直接通過標簽來 find,一般如下:
標簽
標簽.someClass
標簽#someID
標簽[target=_blank]
參數 first 是 True,表示只返回 Element 找到的第一個,更多使用:http://html.python-requests.org/ ;

2、這裏保存本地路徑 /Users/wuxiaolong/Desktop/Girl/我寫死了,需要讀者改成自己的,如果直接是文件名,保存路徑將是項目目錄下。

遺留問題

示例所爬網站是分頁的,沒有做,可以定時循環來爬妹紙哦,有興趣的讀者自己玩下。

參考

requests-html

今天用了一下Requests-HTML庫(Python爬蟲)

公眾號

我的公眾號:吳小龍同學,歡迎交流~
技術分享圖片

Python 爬蟲實戰(二):使用 requests-html