当前位置: 首页>>代码示例>>Python>>正文


Python Browser.screenshot方法代码示例

本文整理汇总了Python中splinter.Browser.screenshot方法的典型用法代码示例。如果您正苦于以下问题:Python Browser.screenshot方法的具体用法?Python Browser.screenshot怎么用?Python Browser.screenshot使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在splinter.Browser的用法示例。


在下文中一共展示了Browser.screenshot方法的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: xfinity

# 需要导入模块: from splinter import Browser [as 别名]
# 或者: from splinter.Browser import screenshot [as 别名]
def xfinity(browser=None):
    if not browser:
        print ("Making browser...")
        browser = Browser('phantomjs')
    print ("Trying google.com...")
    browser.visit('http://google.com/')
    if 'google.' in browser.url:
        print ("google.com connected :)")
        return

    print ("Sign up...")
    browser.click_link_by_partial_text('Sign up')
    print ("Filling form...")
    browser.select("rateplanid", "spn")
    browser.check('spn_terms')
    browser.fill('spn_postal', '12345')
    browser.fill('spn_email', '[email protected]')
    print ("Submitting...")
    sleep(3) # it did not work without the sleeps
    browser.find_by_css('.startSessionButton').type(' \n')
    sleep(7)
    browser.ensure_success_response()
    print (browser.screenshot())
开发者ID:andres-erbsen,项目名称:cogs,代码行数:25,代码来源:xfinity.py

示例2: DakokuWorker

# 需要导入模块: from splinter import Browser [as 别名]
# 或者: from splinter.Browser import screenshot [as 别名]
class DakokuWorker(object):
    def __init__(self, host, user, password, holidays, capture_dir=None):
        self.host = host
        self.user = user
        self.password = password
        self.holidays = holidays
        self.capture_dir = capture_dir
        self.browser = None

    def _is_same_day(self, t1, t2):
        return t1.strftime('%Y%m%d') == t2.strftime('%Y%m%d')

    def _is_holiday(self, t):
        for h in self.holidays:
            if self._is_same_day(t, h): return True
        return False

    def _login(self):
#        self.browser = Browser("phantomjs", user_agent="Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.125 Safari/537.36")
        self.browser = Browser("firefox")
        self.browser.visit(self.host)
        self.browser.fill('user_id', self.user)
        self.browser.fill('password', self.password)
        try:
            log.info("logging in: %s", self.browser.title.decode('utf-8'))
        except:
            log.info("logging in: %s", self.browser.title)

    def work_start(self):
        now_time = dt.datetime.now().replace(tzinfo=pytz.timezone('Asia/Tokyo'))
        try:
            if self._is_holiday(now_time):
                log.info("Today is holiday! Skipping...")
                return
            self._login()
            if self.browser.is_element_present_by_name("syussya", wait_time=5):
                self.browser.find_by_name("syussya").click()
            else:
                log.error("failed to load web page")
                return
            log.info(now_time.strftime("work started at %Y-%m-%d %H:%M:%S"))
            if self.capture_dir:
                capture_path = os.path.join(self.capture_dir, now_time.strftime('syussya_%Y-%m-%d-%H:%M:%S.jpg'))
                tmppath = self.browser.screenshot(suffix="jpg")
                log.info("captured: %s", tmppath)
                shutil.copyfile(tmppath, capture_path)
                log.info("copied to: %s", capture_path)
        except Exception as e:
            log.error("failed to start work: %s", str(e))
        finally:
            self.browser.quit()

    def work_end(self):
        now_time = dt.datetime.now().replace(tzinfo=pytz.timezone('Asia/Tokyo'))
        try:
            if self._is_holiday(now_time):
                log.info("Today is holiday! Skipping...")
                return
            self._login()
            if self.browser.is_element_present_by_name("taisya", wait_time=5):
                self.browser.find_by_name("taisya").click()
            else:
                log.error("failed to load web page")
                return
            log.info(now_time.strftime("work ended at %Y-%m-%d %H:%M:%S"))
            if self.capture_dir:
                capture_path = os.path.join(self.capture_dir, now_time.strftime('taisya_%Y-%m-%d-%H:%M:%S.jpg'))
                tmppath = self.browser.screenshot(suffix="jpg")
                log.info("captured: %s", tmppath)
                shutil.copyfile(tmppath, capture_path)
                log.info("copied to: %s", capture_path)
        except Exception as e:
            log.error('failed to end work: %s', str(e))
        finally:
            self.browser.quit()
开发者ID:furushchev,项目名称:dakoku,代码行数:77,代码来源:dakoku.py

示例3: Browser

# 需要导入模块: from splinter import Browser [as 别名]
# 或者: from splinter.Browser import screenshot [as 别名]
from splinter import Browser

# Your ID Password
user_email = "nishnik"
user_pass = "pass"
browser= Browser('firefox')
browser.visit('http://www.facebook.com')

browser.fill('email', user_email)
browser.fill('pass', user_pass)

button = browser.find_by_id('loginbutton')
button.click()

# Paste the url you need to download from. Note: It must be from mobile site
browser.visit('https://m.facebook.com/photo.php?fbid=780845462017409&id=100002758879147&set=oa.876940942416747&relevant_count=1&source=48&refid=18&_ft_=qid.6274517251577062760%3Amf_story_key.876940939083414%3Atl_objid.876940939083414')
# The number of consecutive pics you have to download
NUM_PICS = 56

i = 0
while i < NUM_PICS:
    i = i + 1
    browser.click_link_by_text('View full size')
    browser.screenshot("screenshot" + str(i) + ".png")
    browser.back()
    browser.click_link_by_text('Next')

browser.quit()
开发者ID:nishnik,项目名称:FacePalm,代码行数:30,代码来源:DigUp.py

示例4: SinaComment

# 需要导入模块: from splinter import Browser [as 别名]
# 或者: from splinter.Browser import screenshot [as 别名]
class SinaComment(object):
    """

    """
    vdisplay = None

    weibo_url = "http://weibo.com/%s/profile"

    def __init__(self, headless=False, driver_name=u'firefox'):
        if headless:
            self.vdisplay = Xvfb()
            self.vdisplay.start()

        if driver_name == u'firefox':
            profile_preferences = {u'permissions.default.stylesheet': 2,
                               u'permissions.default.image': 2,
                               u'dom.ipc.plugins.enabled.libflashplayer.so':
                                      u'false'
            }
            #self.browser = Browser(driver_name, profile_preferences=profile_preferences)
            self.browser = Browser(driver_name)
        else:
            self.browser = Browser(driver_name)

    def __del__ (self):
        self.browser.quit()
        if self.vdisplay is not None:
            self.vdisplay.stop()

    def login(self, user_name=u"**", user_password=u"**"):
        self.browser.visit(u"http://www.weibo.com/login.php")
        if not self.browser.status_code.is_success():
            return False

        self.browser.find_by_xpath('//div[@class="W_login_form"]/div/div/input[@name="username"]').\
            first.fill(user_name)

        password = self.browser.find_by_xpath('//div[@class="W_login_form"]/div/div/input[@name="password"]').first
        password.click()
        password.fill(user_password)

        submit = self.browser.find_by_xpath('//div[@class="W_login_form"]/div/a[@action-type="btn_submit"]').first

        for i in xrange(0, 3):
            submit.click()
            time.sleep(5)
            verify_code =  self.browser.find_by_name("verifycode")
            if len(verify_code) == 0:
                break

            if verify_code.visible:
                verify_code_img  = self.browser.find_by_xpath('//img[@node-type="verifycode_image"]').first
                now_time = int(time.time())
                screenshot_name = self.browser.screenshot("%s_%s" % (user_name,  now_time))
                print u"需要验证码", screenshot_name
                verify_code_text = raw_input(u"输入验证码:")
                verify_code.fill(verify_code_text)
                continue

        if self.browser.url.find(u"home") >= 0:
            return True

        return False


    def reload(self):
        """
        Revisits the current URL
        :return:
        """
        self.browser.reload()

    def comment(self, to_uid, content):
        self.browser.visit(self.weibo_url % to_uid)

        #self.browser.visit(self.weibo_url % to_uid)
        if not self.browser.status_code.is_success():
            return False


        comments = self.browser.find_by_xpath('//span[@node-type="comment_btn_text"]')

        if comments.is_empty():
            print u"用户没有微博"
            return True

        wait_time = 1
        try_count = 0
        for comment in comments:
            if try_count >= 3:
                break
            try:
                comment.mouse_over()
                comment.click()
            except Exception, e:
                print u"点击评论按钮失败"
                print e.message
                continue

            try:
#.........这里部分代码省略.........
开发者ID:oudb,项目名称:weibo_automation,代码行数:103,代码来源:sina_comment2.py

示例5: Browser

# 需要导入模块: from splinter import Browser [as 别名]
# 或者: from splinter.Browser import screenshot [as 别名]
port = 80

# for firefox driver
proxy = {
    'network.proxy.type': 1,
    'network.proxy.http': ip,
    'network.proxy.http_port': port,
    'network.proxy.ssl': ip,
    'network.proxy.ssl_port': port,
    'network.proxy.socks': ip,
    'network.proxy.socks_port': port,
    'network.proxy.ftp': ip,
    'network.proxy.ftp_port': port           
}


# for phantomjs driver
service_args = [
    '--proxy='+ip+":"+str(port),
    '--proxy-type=https',
] 

#browser = Browser('firefox', user_agent=user_agent, profile_preferences=proxy)
browser = Browser('phantomjs', user_agent=user_agent, service_args=service_args)

browser.visit('https://duckduckgo.com/?q=ip')
browser.screenshot(name=BASE_PATH, suffix='_ip.png')

browser.visit('https://duckduckgo.com/?q=user+agent')
browser.screenshot(name=BASE_PATH, suffix='_useragent.png')
开发者ID:urkh,项目名称:splinter_tests,代码行数:32,代码来源:splinter_app.py

示例6: __init__

# 需要导入模块: from splinter import Browser [as 别名]
# 或者: from splinter.Browser import screenshot [as 别名]

#.........这里部分代码省略.........
				# If reply button is invisible
				if not reply.visible:
					# Click checkbox to remove autosend
					self.browser.find_by_css("a[role='checkbox']")[0].click()
				reply.click()	
				self.curr_url = self.browser.url 
			else:
				print "Could not find reply button."
		except URLError:
			print "Connection refused: try restarting the app or logging in again."	

	# Get list of new messages you have 
	def new_messages(self):
		pass

	# Create name to user id mapping 
	def __init_friends(self):
		friends = {}
		# Check for friend file 
		try:
			friend_lines = open("friend_ids.tsv").read().splitlines()
			for line in friend_lines:
				name, fid, username = line.split('\t')
				# Store first name and potential last names with ids 
				first = name.split('_')[0]
				last = name.split('_')[1]
				try:
					friends[first].append((last, fid, username))
				except KeyError:
					friends[first] = [(last, fid, username)]
		# If friend file hasn't yet been created, go through 
		# recent friends and find their names/ids 				
		except IOError:
			friend_file = open("friend_ids.tsv", "w")	
			self.browser.visit(_base_msg_url)
			self.curr_url = self.browser.url 
			recent_users = self.browser.find_by_css("li._k-")
			for user in recent_users:
				try:
					fid = user['id'].split(':')[2]
					name = user.find_by_css("span.accessible_elem").text.lower() 
					username = user.find_by_css("a._k_")['href'].split("/")[-1]
					try:
						first = name.split()[0]
						last = name.split()[1]
					except IndexError:
						continue
					friend_file.write(first + '_' + last + '\t' + fid + '\t' + username + '\n')
					try:
						friends[first].append((last, fid, username))
					except KeyError:
						friends[first] = [(last, fid, username)]
				except StaleElementReferenceException:
					continue
			friend_file.close()
		return friends 

	# Used to initialize the aliases dictionary with 
	# friend names/usernames from previous sessions. 
	def __init_aliases(self):
		aliases = {}
		try:
			# Friends file should be in name,username format 
			with open(_friends_file, "r") as f:
				lines = f.read().splitlines()
				for line in lines:
					name, username = line.split(",")
					aliases[name] = username 
				return aliases 
		# If the file does not exist, create it 
		except IOError:
			f = open(_friends_file, "w")
			f.close()
			return {}

	def update_friend_file(self, name=None, username=None):
		with open(_friends_file, "a") as f:
			if name and username:
				f.write(name + "," + username + "\n")
			else:
				for name, username in self.aliases.iteritems():
					f.write(name + "," + username + "\n")


	def add_alias(self, username, name, force=False):
		# Check to see if name already exists 
		try:
			self.aliases[name]
			if force:
				raise KeyError
			else:
				print "The name already exists. Use force=True to overwrite."
		# If name exists, update dictionary and file 
		except KeyError:
			self.aliases[name] = username
			self.update_friend_file(name=name, username=username)

	def take_screenshot(self, path):
		location = self.browser.screenshot(path)
		print "Saved in:", location 
开发者ID:krisbrown,项目名称:shell-messenger,代码行数:104,代码来源:messenger.py


注:本文中的splinter.Browser.screenshot方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。