selenium+python 爬取網路圖片(2) -- 百度
上一篇博文《selenium+python 爬取網路圖片(1) -- soso、谷歌、好搜》介紹瞭如何用selenium+python在諸如soso、谷歌、好搜等搜尋引擎上爬取圖片的方法,但是卻沒用提到百度,因為百度的情況比較特殊。首先,百度圖片的資料更好,因為每幅圖片都有“data-desc”描述可以作為影象很好的語義標籤,此外基於百度較強的技術其查詢搜尋得到的圖片相關性較高,後續人工篩選工作較少;其次,百度圖片的資料不容易爬取,如果像前一篇文章中的方法取img標籤的src值作為下載url,是下載不到圖片的,得到的知識167B的非影象資料。
那麼,如何爬取百度圖片呢,筆者嘗試了兩種方法。第一種方法尚未完整實現,但思路已完整,第二種方法可以較為簡單的爬到百度圖片資料來源。下面依次介紹兩種實現方案。
方案1:
使用selenium模擬滑鼠操作--“將滑鼠放置影象上方,右鍵並選擇影象另存為選項”,然後就可以儲存了,程式碼如下:
但是,想必大家都會發現,儲存圖片還需要一次次點選對話方塊的確認儲存,很繁瑣。的確,為了解決這個問題,我google了好久並沒有找到直接解決的好方法,根本原因是selenium無法操作作業系統級的對話方塊,有說上面“set profile”程式碼段的設定能解決問題的並不靠譜。所以,如果採用右鍵另存為的方案的話,需要額外使用外掛或鉤子程式模擬自動點選。網上有推薦一個AutoIT的或可完成任務,未親試。from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.common.keys import Keys # init url = 'http://image.baidu.com/i?tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=-1&st=-1&fm=index&fr=&sf=1&fmq=&pv=&ic=0&nc=1&z=&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&ie=utf-8&word=%E6%89%8B%E6%9C%BA&oq=shouji&rsp=1' xpath = '//ul/li/div/a/img' # set profile fp = webdriver.FirefoxProfile() fp.set_preference('browser.download.folderList', 2) fp.set_preference('browser.download.manager.showWhenStarting', False) fp.set_preference('browser.download.dir', './yourfolder/') fp.set_preference('browser.helperApps.neverAsk.saveToDisk', 'image/jpeg') # launch driver driver = webdriver.Firefox(firefox_profile=fp) driver.maximize_window() driver.get(url) for element in driver.find_elements_by_xpath(xpath): img_url = element.get_attribute('src') img_desc = element.get_attribute('data-desc') action = ActionChains(driver).move_to_element(element) action.context_click(element) action.send_keys(Keys.ARROW_DOWN) action.send_keys('v') action.perform() # click save image driver.close()
方案2:
百度圖片img標籤內含的src並不能下載到原圖片,只有data-desc屬性可用,但是,當滑鼠放在百度圖片上時,會發現如下圖所示的下載按鈕,
只要找到這個上面這個下載按鈕對應的連結即可下載到原圖,而按鈕對應的則是一個a連結標籤,分析出其xpath問題即解決了,下面給出python程式碼:
import urllib
import time
from selenium import webdriver
class Crawler:
def __init__(self):
self.url = 'http://image.baidu.com/i?tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=-1&st=-1&fm=index&fr=&sf=1&fmq=&pv=&ic=0&nc=1&z=&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&ie=utf-8&word=%E6%89%8B%E6%9C%BA&oq=shouji&rsp=1' # url to crawl
self.img_xpath = '//ul/li/div/a/img' # xpath of img element
self.download_xpath = '//ul/li/div/div/span/a[@class="downloadicon"]' # xpath of download link element
self.img_url_dic = {}
# kernel function
def launch(self):
# launch driver
driver = webdriver.Firefox()
driver.maximize_window()
driver.get(self.url)
img_xpath = self.img_xpath
download_xpath = self.download_xpath
img_url_dic = self.img_url_dic
# 模擬滾動視窗以瀏覽下載更多圖片
pos = 0
for i in range(10):
pos += i*500 # 每次下滾500
js = "document.documentElement.scrollTop=%d" % pos
driver.execute_script(js)
# get image desc and download
for img_element, link_element in zip(driver.find_elements_by_xpath(img_xpath), driver.find_elements_by_xpath(download_xpath)):
img_desc = img_element.get_attribute('data-desc') # description of image
img_desc = self.filter_filename_str(img_desc)
img_url = link_element.get_attribute('href') # url of source image
if img_url != None and not img_url_dic.has_key(img_url):
img_url_dic[img_url] = ''
ext = img_url.split('.')[-1]
filename = img_desc + '.' + ext
print img_desc, img_url
urllib.urlretrieve(img_url, './yourfolder/%s' % filename)
time.sleep(1)
driver.close()
# filter invalid characters in filename
def filter_filename_str(self, s):
invalid_set = ('\\','/',':','*','?','"','<','>','|',' ')
for i in invalid_set:
s = s.replace(i, '_')
return s
if __name__ == '__main__':
crawler = Crawler()
crawler.launch()
爬取後的結果圖如下所示:
以上程式碼僅示例的實現了方案,驗證其可行性,內部可能含有部分疏漏,僅供需要的朋友參考,不妥之處請指正。
相關推薦
selenium+python 爬取網路圖片(2) -- 百度
上一篇博文《selenium+python 爬取網路圖片(1) -- soso、谷歌、好搜》介紹瞭如何用selenium+python在諸如soso、谷歌、好搜等搜尋引擎上爬取圖片的方法,但是卻沒用提到百度,因為百度的情況比較特殊。首先,百度圖片的資料更好,因為每幅圖片都有
python 爬取動態網頁(百度圖片)
# python 3.6.3 import re import os from urllib import parse from urllib import request ################################################### # 搜尋關鍵字
爬取動態圖片—以百度圖片為例
python爬蟲;人工智能一:何謂動態加載圖片 所謂動態加載圖片即指html剛加載時,圖片時沒有的,然後通過json發生有關圖片的數據,在插入到html裏面去,以到底快速打開網頁的目的,那麽問題來了?我們如何找到加載文件的json文件呢?而這個問題正是我們實現爬取百度圖片的第一步,讓小可愛告訴你怎麽做吧
Python網路爬蟲(四):selenium+chrome爬取美女圖片
說明: Python版本:Python IDE:PyCharm chrome版本:我的版本63 chromedriver.exe:因為是模擬瀏覽器訪問,chrome需要再下載一個驅動,具體方式在我的上一篇部落格,內容很詳細。傳送門:Python網路爬蟲(
python爬取網頁圖片
ima com col list https pytho 表達式 images 5% 在Python中使用正則表達式,一個小小的爬蟲,抓取百科詞條網頁的jpg圖片。下面就是我的代碼,作為參考: #coding=utf-8 # __author__ = ‘Hinfa‘ im
Python 爬取美女圖片,分目錄多級存儲
port Language resp pac rst apt itl album domain 最近有個需求:下載https://mm.meiji2.com/網站的圖片。 所以簡單研究了一下爬蟲。 在此整理一下結果,一為自己記錄,二給後人一些方向。 爬取結果如圖:
selenium+python爬取數據跳轉網頁
tns pen 得出 items search ems find option http 項目要做一個四個層級欄的數據抓取,而且點擊查詢後數據會在新跳出的網頁。 源碼如下 註釋解釋 from selenium import webdriver import seleniu
selenium+python爬取資料跳轉網頁
專案要做一個四個層級欄的資料抓取,而且點選查詢後資料會在新跳出的網頁。 原始碼如下 註釋解釋 from selenium import webdriver import selenium #from time import sleep as sp url='http://202.127.42.15
用python爬取美女圖片
import urllib.request import os for i in range(2000, 2400): if not os.path.exists(‘tupian/’ + str(i)): os.makedirs(‘tupian/’ + str(i)) for j in
python爬取許多圖片的程式碼
from bs4 import BeautifulSoup import requests import os os.makedirs('./img/', exist_ok=True) URL = "http://www.nationalgeographic.com.cn/animals/" htm
Selenium+Python爬取房天下二手房資料
注意!注意!注意!本文中大圖較多,建議使用PC檢視,手機端效果較差! 在上篇“Selenuim+Python網路爬蟲基礎講解”博文中講了一些Selenium的基礎知識,接下來就要開始實戰了。 其實使用Selenium爬取網頁的思路很簡單,首先梳理一下爬取流程。 開啟二手房珠海地區首頁
教你如何用Python爬取美女圖片
Python爬取美女圖片 今天我寫的一個小爬蟲是爬取美女的圖片,想必大家都喜歡,這個都懂。。。 利用python爬蟲爬取圖片,首先要進行安裝python 安裝python之後,在進行安裝第三方庫,requests,bs4,lxml這三個庫。。。 在cmd中 進行
python爬取單張圖片
import urllib.request response = urllib.request.urlopen("http://pic36.photophoto.cn/20150728/0022005597823716_b.jpg") #圖片地址 cat_img = response.read
使用Python爬取網頁圖片
使用Python爬取網頁圖片 李曉文 21 天前 近一段時間在學習如何使用Python進行網路爬蟲,越來越覺得Python在處理爬蟲問題是非常便捷的,那麼接下來我就陸陸續續的將自己學習
python3程式設計08-爬蟲實戰:爬取網路圖片
本篇部落格爬取內容如下: 爬取校花網的圖片 準備工作: 1.安裝python3 2.安裝pycharm 3.安裝Scrapy,參考:Scrapy安裝 cmd命令新建Scrapy工程 1. 在D:\PythonProjects目錄下新建
Python 爬取網頁圖片
可以看到該頁面上每一個圖片點進去是一個套路連結,我想要爬取的是每一個套圖內的所有圖片。同時這個網頁是翻頁的,拉倒最後可以看到。 因此我需要獲取每一頁的html,從這個html中得到所有套圖的連結。下載所有套圖。 1、在Chrome瀏覽器中,點選
用python 爬取網頁圖片
import re import string import sys import os import urllib url="http://tieba.baidu.com/p/2521298181"#這個是某貼吧地址 imgcontent=urllib.urlopen(
python 爬取指定圖片並將圖片下載到指定資料夾
""" Version 1.1.0 Author lkk Email [email protected] date 2018-10-19 11:34 DESC 下載指定網頁的圖片到指定資料夾
利用python爬取網頁圖片
學習python爬取網頁圖片的時候,可以通過這個工具去批量下載你想要的圖片 開始正題: 我從尤物網去爬取我喜歡的女神的寫真照,我們這裡主要用到的就兩個模組 re和urllib模組,有的時候可能會用
使用Python爬取網站圖片
最終程式碼:import requests import json import urllib def getSogouImag(category,length,path): n = length cate = category imgs = requests.get('http://pic.sogou.co