zoukankan      html  css  js  c++  java
  • 使用webdriver和beautifulsoup下载国家地理图片

    很久之前下载过,最近再看国家地理每日一图的时候,发现图片的形式变了,见http://photography.nationalgeographic.com/photography/photo-of-the-day

    看到上面的previous链接,忽然想到自己最近也在研究webdriver,顺便可以使用之下载图片

    使用beautifulsoup下载图片的原理,就是使用urllib打开目标URL,使用beautifulsoup去封装读取内容,然后找到文件的属性:这里可以直接去定位,或者使用正则表达式.webdriver在这里的作用是点页面上的previous链接,然后在每个新的页面去定位要下载的图片.最后使用urlretrieve方法把图片下载到本地.

    import urllib
    from selenium import webdriver
    import os
    from bs4 import BeautifulSoup as BS
    
    base_dir = os.path.join(os.getcwd(), "nationalgeographic")
    if not os.path.exists(base_dir):
        os.mkdir(base_dir)
        
    base_url = 'http://photography.nationalgeographic.com/photography/photo-of-the-day'
    
    driver = webdriver.Firefox()
    driver.get(base_url)
    
    previois_link = driver.find_element_by_partial_link_text('Previous')
    
    while previois_link:
        print 'current url is: ', driver.current_url
        content = urllib.urlopen(driver.current_url).read()
        soup = BS(content)
        urls = soup.findAll('img', width = '990')
        for url in urls:
            url = url["src"]
            filename = base_dir + '\\' + url.split('/')[-1]
            urllib.urlretrieve(url, filename)
            print 'download', filename, 'to', base_dir
        previois_link = driver.find_element_by_partial_link_text('Previous')
        previois_link.click()
        driver.refresh()
        print 'after refresh', driver.current_url
    作者:Shane
    出处:http://bluescorpio.cnblogs.com
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
  • 相关阅读:
    MyEclipse 8.5 M1注册码(转)
    非常经典有深度的电影英文台词(转)
    pb函数库 DataWindow常用函数(转)
    35岁以前把下面十件事做好(转)
    相识如茶,相思似酒(转)
    常用的SQL 脚本
    SQL Server Mobile 数据类型
    人生的35个好习惯 给人生的25条建议(转)
    sybase数据库相关
    模板
  • 原文地址:https://www.cnblogs.com/bluescorpio/p/2497740.html
Copyright © 2011-2022 走看看