summaryrefslogtreecommitdiffstats
path: root/tools/site_compare/scrapers/chrome/chromebase.py
blob: 085f3764d5bf6900e1d7aae332e4badae5ecd5eb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
#!/usr/bin/python2.4
# Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Does scraping for all currently-known versions of Chrome"""

import pywintypes
import types

from drivers import keyboard
from drivers import mouse
from drivers import windowing

# TODO: this has moved, use some logic to find it. For now,
# expects a subst k:.
DEFAULT_PATH = r"k:\chrome.exe"

def InvokeBrowser(path):
  """Invoke the Chrome browser.
  
  Args:
    path: full path to browser
      
  Returns:
    A tuple of (main window, process handle, address bar, render pane)
  """
    
  # Reuse an existing instance of the browser if we can find one. This
  # may not work correctly, especially if the window is behind other windows.
  
  # TODO(jhaas): make this work with Vista
  wnds = windowing.FindChildWindows(0, "Chrome_XPFrame")
  if len(wnds):
    wnd = wnds[0]
    proc = None
  else:
    # Invoke Chrome
    (proc, wnd) = windowing.InvokeAndWait(path)
  
  # Get windows we'll need
  address_bar = windowing.FindChildWindow(wnd, "Chrome_AutocompleteEdit")
  render_pane = GetChromeRenderPane(wnd)
  
  return (wnd, proc, address_bar, render_pane)

  
def Scrape(urls, outdir, size, pos, timeout, kwargs):
  """Invoke a browser, send it to a series of URLs, and save its output.
  
  Args:
    urls: list of URLs to scrape
    outdir: directory to place output
    size: size of browser window to use
    pos: position of browser window
    timeout: amount of time to wait for page to load
    kwargs: miscellaneous keyword args
  
  Returns:
    None if success, else an error string
  """
  if "path" in kwargs and kwargs["path"]: path = kwargs["path"]
  else: path = DEFAULT_PATH
  
  (wnd, proc, address_bar, render_pane) = InvokeBrowser(path)
  
  # Resize and reposition the frame
  windowing.MoveAndSizeWindow(wnd, pos, size, render_pane)
  
  # Visit each URL we're given
  if type(urls) in types.StringTypes: urls = [urls]

  timedout = False
  
  for url in urls:
    # Double-click in the address bar, type the name, and press Enter
    mouse.ClickInWindow(address_bar)
    keyboard.TypeString(url, 0.1)
    keyboard.TypeString("\n")
    
    # Wait for the page to finish loading
    load_time = windowing.WaitForThrobber(wnd, (20, 16, 36, 32), timeout)
    timedout = load_time < 0
    
    if timedout:
      break
    
    # Scrape the page
    image = windowing.ScrapeWindow(render_pane)
    
    # Save to disk
    if "filename" in kwargs:
      if callable(kwargs["filename"]):
        filename = kwargs["filename"](url)
      else:
        filename = kwargs["filename"]
    else:
      filename = windowing.URLtoFilename(url, outdir, ".bmp")
    image.save(filename)
  
  if proc:
    windowing.SetForegroundWindow(wnd)
    
    # Send Alt-F4, then wait for process to end
    keyboard.TypeString(r"{\4}", use_modifiers=True)
    if not windowing.WaitForProcessExit(proc, timeout):
      windowing.EndProcess(proc)
      return "crashed"
    
  if timedout:
    return "timeout"
  
  return None


def Time(urls, size, timeout, kwargs):
  """Measure how long it takes to load each of a series of URLs
  
  Args:
    urls: list of URLs to time
    size: size of browser window to use
    timeout: amount of time to wait for page to load
    kwargs: miscellaneous keyword args
  
  Returns:
    A list of tuples (url, time). "time" can be "crashed" or "timeout"
  """
  if "path" in kwargs and kwargs["path"]: path = kwargs["path"]
  else: path = DEFAULT_PATH
  proc = None
  
  # Visit each URL we're given
  if type(urls) in types.StringTypes: urls = [urls]
  
  ret = []
  for url in urls:
    try:
      # Invoke the browser if necessary
      if not proc:
        (wnd, proc, address_bar, render_pane) = InvokeBrowser(path)
        
        # Resize and reposition the frame
        windowing.MoveAndSizeWindow(wnd, (0,0), size, render_pane)
        
      # Double-click in the address bar, type the name, and press Enter
      mouse.ClickInWindow(address_bar)
      keyboard.TypeString(url, 0.1)
      keyboard.TypeString("\n")
      
      # Wait for the page to finish loading
      load_time = windowing.WaitForThrobber(wnd, (20, 16, 36, 32), timeout)
      
      timedout = load_time < 0
      
      if timedout:
        load_time = "timeout"
        
        # Send an alt-F4 to make the browser close; if this times out,
        # we've probably got a crash
        windowing.SetForegroundWindow(wnd)
      
        keyboard.TypeString(r"{\4}", use_modifiers=True)
        if not windowing.WaitForProcessExit(proc, timeout):
          windowing.EndProcess(proc)
          load_time = "crashed"
        proc = None
    except pywintypes.error:
      proc = None
      load_time = "crashed"
            
    ret.append( (url, load_time) )

  if proc:    
    windowing.SetForegroundWindow(wnd)
    keyboard.TypeString(r"{\4}", use_modifiers=True)
    if not windowing.WaitForProcessExit(proc, timeout):
      windowing.EndProcess(proc)

  return ret


if __name__ == "__main__":
  # We're being invoked rather than imported, so run some tests
  path = r"c:\sitecompare\scrapes\chrome\0.1.97.0"
  windowing.PreparePath(path)
  
  # Scrape three sites and save the results
  Scrape([
    "http://www.microsoft.com",
    "http://www.google.com",
    "http://www.sun.com"],
         path, (1024, 768), (0, 0))