本文整理汇总了Python中pyvirtualdisplay.Display.start方法的典型用法代码示例。如果您正苦于以下问题:Python Display.start方法的具体用法?Python Display.start怎么用?Python Display.start使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pyvirtualdisplay.Display
的用法示例。
在下文中一共展示了Display.start方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_driver
# 需要导入模块: from pyvirtualdisplay import Display [as 别名]
# 或者: from pyvirtualdisplay.Display import start [as 别名]
def get_driver(browser, display):
dricve=1
if display==0:
display = Display(visible=0, size=(800, 600))
display.start()
if browser and 'chrome' in browser.lower():
options = webdriver.ChromeOptions()
#prefs = {"download.default_directory" : folder}
options.add_argument('--user-agent={}'.format(random.choice(USER_AGENTS)))
options.add_experimental_option("prefs",prefs)
if dricve == 1:
return webdriver.Chrome(chrome_options=options)
else:
return webdriver.PhantomJS()#
else:
profile = webdriver.FirefoxProfile()
profile.set_preference('general.useragent.override', random.choice(USER_AGENTS))
#profile.set_preference("browser.download.folderList",2);
#profile.set_preference("browser.download.manager.showWhenStarting",false);
#profile.set_preference("browser.download.dir",folder);
profile.set_preference('browser.helperApps.neverAsk.saveToDisk', 'application/zip')
return webdriver.Firefox(profile)
示例2: Xvfb
# 需要导入模块: from pyvirtualdisplay import Display [as 别名]
# 或者: from pyvirtualdisplay.Display import start [as 别名]
class Xvfb(object):
def __init__(self, width=1366, height=768, visible=0):
self.__virtual_display = None
self.width = width
self.height = height
self.visible = visible
def __init_display(self):
if self.__virtual_display is None:
self.__virtual_display = Display(visible=self.visible, size=(self.width, self.height))
self.__virtual_display.start()
def __enter__(self):
self.__init_display()
def __exit__(self, exc_type, exc_val, exc_tb):
self._close_display()
def _close_display(self):
if self.__virtual_display:
try:
self.__virtual_display.close()
except:
pass
self.__virtual_display = None
@staticmethod
def run(func, *args, **kwargs):
runner = Xvfb()
with runner:
return func(*args, **kwargs)
示例3: UITestCase
# 需要导入模块: from pyvirtualdisplay import Display [as 别名]
# 或者: from pyvirtualdisplay.Display import start [as 别名]
class UITestCase(LiveServerTestCase):
def use_xvfb(self):
from pyvirtualdisplay import Display
self.display = Display('xvfb',
visible=1,
size=(1280, 1024))
self.display.start()
self.driver = WebDriver()
def setUp(self):
try:
self.driver = WebDriver()
ui_is_not_available = False
except WebDriverException:
ui_is_not_available = True
if ui_is_not_available:
self.use_xvfb()
self.driver.implicitly_wait(10)
super(UITestCase, self).setUp()
def tearDown(self):
self.driver.quit()
if hasattr(self, 'display'):
self.display.stop()
super(UITestCase, self).tearDown()
示例4: load
# 需要导入模块: from pyvirtualdisplay import Display [as 别名]
# 或者: from pyvirtualdisplay.Display import start [as 别名]
def load(self):
min_time = 3600 # 1 hour in seconds
max_time = 7179 # 2 hours in seconds (less 21)
tasktime = randint(min_time, max_time)
threading.Timer(tasktime, self.load).start()
tasktime_m , tasktime_s = divmod( tasktime , 60)
tasktime_h , tasktime_m = divmod( tasktime_m , 60)
output_content = "Load execution - waiting %dh %02dmin %02dsec for the next time." % (tasktime_h, tasktime_m, tasktime_s)
print "[KeepUp]" , output_content
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.common.keys import Keys
from pyvirtualdisplay import Display
# Initial
display = Display(visible=0, size=(1600, 900))
display.start()
profile = webdriver.FirefoxProfile()
profile.set_preference("browser.cache.disk.enable", False)
profile.set_preference("browser.cache.memory.enable", False)
profile.set_preference("browser.cache.offline.enable", False)
profile.set_preference("network.http.use-cache", False)
driver = webdriver.Firefox()
driver.get("https://c9.io/dashboard.html")
driver.save_screenshot(self.directory_img + 'login.png')
#Username
username = driver.find_element_by_id("id-username")
username.click()
username.clear()
username.send_keys(self.user, Keys.ARROW_DOWN)
#Password
password = driver.find_element_by_id("id-password")
password.click()
password.clear()
password.send_keys(self.password, Keys.ARROW_DOWN)
#Submit
submit_button = driver.find_element_by_css_selector("button[type=submit]")
# print submit_button.text
# Click submition
submit_button.click();
time.sleep(5)
driver.save_screenshot(self.directory_img + 'user_profile.png')
# Target dir
driver.get(self.target_workspace)
time.sleep(10)
self.log({'log_html': driver.page_source, 'log_file': output_content}) #make log
driver.save_screenshot(self.directory_img + 'final_workspace.png')
# End
driver.quit()
display.stop()
示例5: getupc
# 需要导入模块: from pyvirtualdisplay import Display [as 别名]
# 或者: from pyvirtualdisplay.Display import start [as 别名]
def getupc(data, sleeptime):
display = Display(visible=0, size=(800, 600))
display.start()
a = webdriver.Firefox()
a.get('https://www.google.com/ncr')
time.sleep(sleeptime)
search = WebDriverWait(a, 5).until(EC.element_to_be_clickable((By.XPATH, "//input[@type='text']")))
for i in data:
ActionChains(a).move_to_element(search).click(search).send_keys(i['name'] + ' upc', Keys.ENTER).perform()
time.sleep(sleeptime)
contents = WebDriverWait(a, 5).until(EC.presence_of_all_elements_located((By.XPATH, "//div[@class='g']")))
try:
upc = next(
(re.split(r'/', href.find_element_by_tag_name('a').get_attribute('href'))[-1] for
href in contents if
href.find_element_by_tag_name('a').get_attribute('href').startswith(
'http://www.upcitemdb.com/upc')))
i['upc'] = upc
except StopIteration:
pass
search = WebDriverWait(a, 5).until(EC.element_to_be_clickable((By.XPATH, "//input[@type='text']")))
search.clear()
a.close()
display.stop()
return data
示例6: process_install_form
# 需要导入模块: from pyvirtualdisplay import Display [as 别名]
# 或者: from pyvirtualdisplay.Display import start [as 别名]
def process_install_form (self):
if (self.args.xvfb):
print "Omeka is being installed in: " + self.folder_name
display = Display(visible=0, size=(800, 600))
display.start()
driver = webdriver.Firefox()
driver.get("http://localhost/omeka/" + self.folder_name + "/install")
inputElement = driver.find_element_by_name("username")
inputElement.send_keys(self.omeka_user)
inputElement = driver.find_element_by_name("password")
inputElement.send_keys(self.omeka_passwd)
inputElement = driver.find_element_by_name("password_confirm")
inputElement.send_keys(self.omeka_passwd)
inputElement = driver.find_element_by_name("super_email")
inputElement.send_keys("[email protected]")
inputElement = driver.find_element_by_name("administrator_email")
inputElement.send_keys("[email protected]")
inputElement = driver.find_element_by_name("site_title")
inputElement.send_keys(self.omeka_title)
inputElement.submit()
try:
WebDriverWait(driver, 10).until(
lambda driver : driver.find_element_by_partial_link_text("Tableau"))
finally:
driver.quit()
示例7: rzhd
# 需要导入模块: from pyvirtualdisplay import Display [as 别名]
# 或者: from pyvirtualdisplay.Display import start [as 别名]
def rzhd():
directions=[create_url(),]
while raw_input('Want to add more directions? y/n ')=='y':
directions.append(create_url())
print "------------------"
# n=raw_input('Check tickets every ...(seconds)? ')
n = 60
place=choose_place()
i = 0
display = Display(visible=0, size=(5, 5))
display.start() # Запускаем вирутальный дисплей
while len(directions)!=0:
i+=1
print
print "----------------->Searching for PLATSKART<-----------------"
print "try #",i
print time.asctime()
print
for url in directions:
if find_train(url, place)==True:
send_email('[email protected]', url)
if raw_input('Did you buy ticket? y/n ')=='y':
directions.remove(url)
if len(directions) == 0:
print "Successfully bought all tickets!"
return True
print str(n)+" seconds until next try..."
time.sleep(float(n)) # Дадим браузеру корректно завершиться
display.stop() # Закрываем виртуальный дисплей
示例8: get_all_items
# 需要导入模块: from pyvirtualdisplay import Display [as 别名]
# 或者: from pyvirtualdisplay.Display import start [as 别名]
def get_all_items():
#list to store alll scraped data
all_items = list()
#Display - read about pyvirtualdisplay
display = Display(visible=0, size=(1024, 768))
display.start()
#webdriver - read about selenium.webdriver
driver = webdriver.Firefox()
#this is a starting page we are scraping
driver.get("http://www.federalreserve.gov/apps/reportforms/default.aspx")
#Every element on the HTML page can be located using CSS selectors.
#Opening the starting page in Chrome, right click on the drop-down menu, click "Inspect" we see a tag on the right highlighted, we copy it's id - MainContent_ddl_ReportForms
#Knowing the id of dropdown menu, we can locate it with Selenium like this
main_menu = WebDriverWait(driver,10).until(EC.presence_of_element_located((By.CSS_SELECTOR,"#MainContent_ddl_ReportForms")))
#Drop down menu is an HTML table of options which can be verified in Chrome browser (Developer Tools, that pop up when you right click and press "Inspect" on an element)
#Following returns all of the options - rows in that table
form_options = main_menu.find_elements_by_tag_name("option")
#We count them
option_count = len(form_options)
#Next, we loop over all of them - essentially like we scrolling down the drop down menu and clicking on each every form
for form_i in xrange(1,option_count):
#Get web element corresponding to a form
form = form_options[form_i]
#Click as a mouse click-action in browser
form.click()
#Get text, because we need to store the form number
form_id = form.text
#Locate a web element corresponding to the submit button. By CSS selector which we found by inspection in Chrome browser (same logic as above)
submit_button = WebDriverWait(driver,3).until(EC.presence_of_element_located((By.CSS_SELECTOR,"#MainContent_btn_GetForm")))
#Click as a mouse click-action in browser
submit_button.click()
#Prepare data structures to store all the info we want to scrape
a = dict.fromkeys(['Description','OMB','Background','RespondentPanel','Frequency','PublicRelease'])
#We are on a web page after submit-click, following will search for all items of interest. Or for corresponding
#web-elements
for el in a.keys():
try:
item = driver.find_element_by_css_selector("#MainContent_lbl_"+el+"_data")
#Once found it will store them in our dictionary, if not it will proceed to "except" section and do nothing
a[el] = item.text
except:
#case when there is no such field
pass
#we need form number as well
a['FormNumber'] = form_id
#keeping them all in one list, which will have a dictionary per Form Number - and later, a row in your excel file per Form number
all_items.append(a)
#Ok, that part bothers me a little: it looks like I have to refresh "form_options" each time...
#Otherwise I get following exception: selenium.common.exceptions.StaleElementReferenceException: Message: Element not found in the cache - perhaps the page has changed since it was looked up
driver.get("http://www.federalreserve.gov/apps/reportforms/default.aspx")
main_menu = WebDriverWait(driver,10).until(EC.presence_of_element_located((By.CSS_SELECTOR,"#MainContent_ddl_ReportForms")))
form_options = main_menu.find_elements_by_tag_name("option")
driver.close()
display.stop()
return all_items
示例9: Spider
# 需要导入模块: from pyvirtualdisplay import Display [as 别名]
# 或者: from pyvirtualdisplay.Display import start [as 别名]
class Spider(scrapy.Spider):
name = "mayors"
allowed_domains = ["www.cec.gov.tw"]
start_urls = ["https://www.cec.gov.tw/pc/zh_TW/IDX/indexC.html",]
download_delay = 1
def __init__(self, ad=None, *args, **kwargs):
super(Spider, self).__init__(*args, **kwargs)
self.display = Display(visible=0, size=(800, 600))
self.display.start()
self.driver = webdriver.Chrome("/var/chromedriver/chromedriver")
def spider_closed(self, spider):
self.display.close()
def parse(self, response):
self.driver.get(response.url)
nodes = scrapy.Selector(text=self.driver.page_source).xpath('//a[@target="_top"]')
for node in nodes:
county = node.xpath('text()').extract_first()
print county
yield response.follow(node, callback=self.parse_list, meta={'meta': county})
def parse_list(self, response):
for tr in response.css(u'table.tableT tr.trT'):
d = {}
d['type'] = 'mayors'
d['county'] = response.meta['meta']
d['constituency'] = 0
d['elected'] = tr.xpath('td[1]/text()').extract_first().strip()
d['number'] = int(tr.xpath('td[2]/text()').extract_first())
d['votes'] = int(re.sub('\D', '', tr.xpath('td[5]/text()').extract_first()))
d['votes_percentage'] = tr.xpath('td[6]/text()').extract_first()
yield d
示例10: openurl
# 需要导入模块: from pyvirtualdisplay import Display [as 别名]
# 或者: from pyvirtualdisplay.Display import start [as 别名]
def openurl(companyname=first_arg):
display = Display(visible=0, size=(1024, 768))
display.start()
browser = webdriver.Firefox()
time.sleep(randint(8,10))
try:
browser.get('http://www.google.com')
time.sleep(5)
search = browser.find_element_by_name('q')
input_text = companyname + str(" crunchbase")
search.send_keys(input_text)
time.sleep(randint(10,15))
search.send_keys(Keys.RETURN)
time.sleep(randint(10,15))
gn = browser.find_element_by_tag_name('h3').text
gnc = str(gn).split(' | ')[0].replace(" ","")
output_file = '0515' + gnc + '.html'
browser.find_element_by_link_text(gn).click()
time.sleep(randint(55,60))
company_html = browser.page_source
time.sleep(randint(5,10))
with open("smallname.txt", 'a') as myfile:
json.dump(output_file,myfile)
with open(output_file, 'a+') as myfile:
myfile.write(company_html)
except:
company_html = 'none'
with open("missedname.txt", "a") as myfile:
json.dump(companyname,myfile)
time.sleep(1)
browser.close()
time.sleep(1)
display.stop()
return company_html
示例11: process_screenshots
# 需要导入模块: from pyvirtualdisplay import Display [as 别名]
# 或者: from pyvirtualdisplay.Display import start [as 别名]
def process_screenshots(app, env):
if not hasattr(env, 'screenshot_all_screenshots'):
return
if not app.config['screenshots_create']:
print("Not doing screenshots on maggies farm no more")
return
if 'SPHINX_SS_USE_PVD' in os.environ.keys() and os.environ['SPHINX_SS_USE_PVD'] == "true":
from pyvirtualdisplay import Display
# Start a virtual headless display
display = Display(visible=0, size=(1024, 768))
display.start()
else:
display = None
# Don't bother building screenshots if we're just collecting messages.
# Just checks if we invoked the build command with "gettext" in there somewhere
if "gettext" in sys.argv:
return
all_args = map(lambda x: x['from_str_arg'], env.screenshot_all_screenshots)
# If building in a different language, start the server in a different language
command = SCREENSHOT_COMMAND + SCREENSHOT_COMMAND_OPTS + \
[re.sub(r"\s", r"", "--from-str={0}".format(json.dumps(all_args)))]
language = env.config.language
if language:
command += ["--lang={0}".format(language)]
subprocess = Popen(command)
subprocess.wait()
try:
if subprocess.returncode:
raise Exception("Screenshot process had nonzero return code: {0}".format(subprocess.returncode))
finally:
if display:
display.stop()
示例12: SeleniumRunner
# 需要导入模块: from pyvirtualdisplay import Display [as 别名]
# 或者: from pyvirtualdisplay.Display import start [as 别名]
class SeleniumRunner(object):
def __call__(self, f):
@functools.wraps(f)
def decorated(_self, *args, **kwargs):
with self as driver:
return f(_self, driver, *args, **kwargs)
return decorated
def __enter__(self):
self.display = Display(visible=0, size=(800, 600))
self.display.start()
self.driver = webdriver.Chrome()
return self.driver
def __exit__(self, *args, **kwargs):
try:
self.driver.quit()
except (AttributeError,) as e:
# Someone has messed with our browser
pass
try:
self.display.stop()
except (AttributeError,) as e:
# Someone has messed with our display
pass
示例13: __init__
# 需要导入模块: from pyvirtualdisplay import Display [as 别名]
# 或者: from pyvirtualdisplay.Display import start [as 别名]
class BrowserManager:
def __init__(self):
self._lock = False
def bootup(self):
self._display = Display(visible=0, size=(1024, 768))
self._display.start()
profile = {}
if 'HTTP_PROXY' in os.environ:
proxy_url = os.environ['HTTP_PROXY']
proxy_server = proxy_url.split(':')[1][2:]
proxy_port = proxy_url.split(':')[-1]
profile['network.proxy.type'] = 1
profile['network.proxy.http'] = proxy_server
profile['network.proxy.http_port'] = proxy_port
profile['network.proxy.https'] = proxy_server
profile['network.proxy.https_port'] = proxy_port
self.browser = Browser(profile_preferences=profile)
def obtain(self,background):
while self._lock:
background.wait('Browser lock', 15)
self._lock = True
return self.browser
def release(self,background):
self._lock = False
def shutdown(self):
self.browser.quit()
self._display.stop()
示例14: virtual_display_if_enabled
# 需要导入模块: from pyvirtualdisplay import Display [as 别名]
# 或者: from pyvirtualdisplay.Display import start [as 别名]
def virtual_display_if_enabled(enabled):
if enabled:
display = Display(visible=0, size=(800, 600))
display.start()
return display
else:
return NoopDisplay()
示例15: main
# 需要导入模块: from pyvirtualdisplay import Display [as 别名]
# 或者: from pyvirtualdisplay.Display import start [as 别名]
def main(args):
parser = argparse.ArgumentParser(description="Program for running tests on the PATRIC web interface.")
parser.add_argument("user", metavar="user", help="Patric login username.")
parser.add_argument("passwd", metavar="passwd", help="Patric login password.")
parser.add_argument("--firebug", action="store_true", help="Open Firebug during test.")
args = parser.parse_args()
fp = webdriver.FirefoxProfile()
if args.firebug:
fp.add_extension(extension='extras/firebug-2.0.9.xpi')
fp.set_preference("extensions.firebug.currentVersion", "2.0.9") #Avoid startup screen
fp.set_preference("extensions.firebug.console.enableSites", "true")
fp.set_preference("extensions.firebug.net.enableSites", "true")
fp.set_preference("extensions.firebug.script.enableSites", "true")
fp.set_preference("extensions.firebug.allPagesActivation", "on")
# Create virtual display
display = Display(visible=0, size=(1400, 950))
display.start()
# Create webdriver and retrieve url
driver = webdriver.Firefox(firefox_profile=fp)
driver.get(SITE_URL + '/login')
# Wait for username input box to appear
WebDriverWait(driver, PAGE_LOAD_TIMEOUT).until(EC.presence_of_element_located((By.ID, "dijit_form_TextBox_0")))
# Set username and password, click login button
userElement = driver.find_element_by_id("dijit_form_TextBox_0")
pwdElement = driver.find_element_by_id("dijit_form_TextBox_1")
userElement.send_keys(args.user)
pwdElement.send_keys(args.passwd)
loginElement = driver.find_element_by_id("dijit_form_Button_1")
loginElement.click()
time.sleep(3)
# Retrieve home page, wait for an expected page element to load, take a screenshot
driver.get(SITE_URL + '/portal/portal/patric/Home')
WebDriverWait(driver, PAGE_LOAD_TIMEOUT).until(EC.presence_of_element_located((By.ID, "cart")))
driver.set_window_size(1400, 950)
driver.execute_script("window.scrollTo(0,0);")
driver.get_screenshot_as_file("homepage_after_login.jpg")
print "Saved screenshot to: homepage_after_login.jpg\n"
# Retrieve ws url, wait for create folder button to appear
ws_url = SITE_URL + '/workspace/' + args.user + '@patricbrc.org/home'
driver.get(ws_url)
WebDriverWait(driver, PAGE_LOAD_TIMEOUT).until(EC.presence_of_element_located((By.CLASS_NAME, "ActionButtonContainer")))
time.sleep(5)
# Have to reload page, because often time the workspace is empty on first load
driver.get(ws_url)
WebDriverWait(driver, PAGE_LOAD_TIMEOUT).until(EC.presence_of_element_located((By.CLASS_NAME, "ActionButtonContainer")))
# createFolderButton = driver.find_element_by_class_name("ActionButton fa icon-folder-plus fa-2x")
# createFolderButton.click()
time.sleep(30)
driver.quit()
display.stop()
return 0