使用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
posted @ 2012-05-13 01:01  小楼  阅读(1647)  评论(0编辑  收藏  举报