用python爬取动态网页上的图片(百度图片)

用python爬取动态网页上的图片(百度图片)
参考B站一个视频,视频链接:
https://www.bilibili.com/video/BV1Va4y1Y7fK?share_source=copy_web
chromedriver.exe驱动下载链接:
http://chromedriver.storage.googleapis.com/index.html

from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
import time
import requests

def getnamepage(name):
    b.get('http://image.baidu.com/')
    #search_box=b.find_element_by_id('kw')
    search_box = b.find_element_by_id('kw')
    search_box.send_keys(name)
    search_box.send_keys(Keys.ENTER)
    time.sleep(5)

def download(imglist,num):
    #选取大尺寸
    ele=b.find_element_by_id('sizeFilter')
    ActionChains(b).move_to_element(ele).perform()
    time.sleep(2)
    #up主的代码
    #ele4=b.find_element_by_xpath('//*[@id="sizeFilter"]/div/ul/li[3]')
    # 我自己的代码,在尺寸里面找的时候多往下层翻一翻,尺寸选择在里面
    ele4 = b.find_element_by_xpath(' // *[ @ id = "sizeFilter"] / div / div[2] / ul / li[3]')
    ActionChains(b).move_to_element(ele4).perform()
    time.sleep(2)
    ele4.click()
    time.sleep(2)

    #打开第一张图片,在此界面中点击左右切换图片
    # up主的代码
    #ele1=b.find_element_by_xpath('/html/body/div[2]/div[2]/div[4]/div/ul/li[1]/div[1]/a/img')
    #我自己的代码
    ele1 = b.find_element_by_xpath('// *[ @ id = "imgid"] / div[1] / ul / li[3] / div / div[2] / a / img')
    ele1.click()
    b.switch_to.window(b.window_handles[1])#很重要的一步,切换窗口,否则页面找不到元素,python shell里面是b.switch_to_window
    x=1
    for i in range(1,num+1):
        #ele3=b.find_element_by_xpath('/html/body/div[1]/div[2]/div/span[2]/span')
        #ele3.click()
        #time.sleep(3)#为保险起见,设置一个睡眠和爬取的时间差
        ele2=b.find_element_by_xpath('//*[@id="currentImg"]')
        img=ele2.get_attribute('src')#获取当前图片的url链接
        r=requests.get(img)
        if r.status_code==200:
            path='F://python-file//picture/%d.jpg'%x
            print('正在爬取  '+img)
            with open(path,'wb') as f:
                f.write(r.content)
                time.sleep(1)
                f.close()
                print('爬取成功')
                x+=1
            ele3=b.find_element_by_xpath('/html/body/div[1]/div[2]/div/span[2]/span')
            ele3.click()
            #time.sleep(3)
        #跳到下一张
        else:
            ele3=b.find_element_by_xpath('/html/body/div[1]/div[2]/div/span[2]/span')
            ele3.click()
            time.sleep(1)
            continue
        

if __name__=="__main__":
    #b=webdriver.Chrome()
    #b = webdriver.Chrome('G:\Google\Chrome\Application//chromedriver.exe')
    #这里的chromedriver.exe驱动需要自己下载,不同谷歌浏览器对应不同的驱动,这个驱动要与谷歌浏览器放在同一个文件夹下
    b = webdriver.Chrome('G://Google//Chrome//Application//chromedriver.exe')
    name='笛卡尔'#定义要搜索的内容
    num=15
    imglist=[]
    getnamepage(name)
    download(imglist,num)
    b.close()

猜你喜欢

转载自blog.csdn.net/yuzhongmanbu99/article/details/123966376