1. 程式人生 > >python3 爬蟲神器pyquery的使用實例

python3 爬蟲神器pyquery的使用實例

open content spa dirname index rom tar requests ()

PyQuery 可讓你用 jQuery 的語法來對 xml 進行操作,這和 jQuery 十分類似。如果利用 lxml,pyquery 對 xml 和 html 的處理將更快。

如果對 jQuery 熟悉,那麽 PyQuery來解析文檔就是不二之選!

下面的例子是爬取 ‘http://so.fengniao.com/index.php?action=Image&keyword=%E7%BE%8E%E6%99%AF‘ 這個頁面的圖片然後保存到本地

 1 from pyquery import PyQuery as pq
 2 import os,requests
 3 targetDir = os.path.join(os.path.dirname(os.path.abspath(__file__
)),imgs1)#圖片保存的路徑 4 if not os.path.isdir(targetDir):#不存在創建路徑 5 os.mkdir(targetDir) 6 doc = pq(http://so.fengniao.com/index.php?action=Image&keyword=%E7%BE%8E%E6%99%AF) 7 imgs = doc(img)#取到所有圖片 8 list_imgs = [] 9 for img in imgs.items(): 10 list_imgs.append(img.attr(src))#將所有圖片鏈接放到列表
11 num = 0 12 for url in list_imgs: 13 r = requests.get(url) 14 image_name = os.path.join(targetDir, str(num) + .jpg)#指定目錄,圖片名‘xx.jpg‘ 15 fw = open(image_name,wb) 16 fw.write(r.content) 17 num +=1 18 fw.close()

python3 爬蟲神器pyquery的使用實例