从selenium保存快照

时间:2015-08-21 11:12:29

标签: python selenium selenium-webdriver operating-system

这是我的代码。

import requests, time, csv, urllib2, math, os, datetime
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from lxml import html
from scrapy import Selector as s

path = "D:\Philip\Snapshot"; mydir = os.path.join(path, datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')); active_directory = os.makedirs(mydir)

stocks_links = ['http://finviz.com/quote.ashx?t=A&b=1',
                'http://finviz.com/quote.ashx?t=AA&b=1',
                'http://finviz.com/quote.ashx?t=AAC&b=1',
                'http://finviz.com/quote.ashx?t=AAL&b=1',
                'http://finviz.com/quote.ashx?t=AAMC&b=1',
                'http://finviz.com/quote.ashx?t=AAME&b=1',
                'http://finviz.com/quote.ashx?t=A&b=1']

driver = webdriver.Chrome()
driver.set_page_load_timeout(30)

def get_stock_symbols(links):
    get3 = requests.get(each)
    source3 = s(text=get3.text,type="html")
    Stock_symbol = source3.xpath('//td[@align="center"]//a[@id="ticker"]/text()').extract()
    Stock_symbol = str(Stock_symbol).replace("u'","").replace("'","")
    print Stock_symbol
    try:
    driver.get(each)
    except Exception:
        pass
    driver.maximize_window()
    driver.execute_script("document.body.style.zoom='90%'")
    driver.execute_script("window.scrollTo(0, 160)")
    time.sleep(2)
    driver.save_screenshot(str(active_directory)+"/"+Stock_symbol+'.jpg')
    time.sleep(2)
    driver.execute_script("document.body.style.zoom='100%'")

for each in stocks_links:
    get_stock_symbols(each)

我执行代码后,我没有看到任何错误,但我的截图不保存在目录中。在OS模块的帮助下,我确实创建了一个目录,但无法在那里看到图像。请帮忙

1 个答案:

答案 0 :(得分:0)

我使用了 - os.path.join