def template(name, contents): cpu_class = 'active' if name == 'cpu' else '' wc_class = 'active' if name == 'wc' else '' help_class = 'active' if name == 'help' else '' return E.HTML( E.HEAD( E.LINK(rel='stylesheet', type='text/css', href='bootstrap/css/bootstrap.css'), E.LINK(rel='stylesheet', type='text/css', href='profile.css'), E.SCRIPT(src='bootstrap/js/bootstrap.min.js'), E.TITLE('RUM Job Profile')), E.BODY( E.DIV(E.DIV(E.DIV(E.A(E.SPAN(CLASS='icon-bar'), E.SPAN(CLASS='icon-bar'), E.SPAN(CLASS='icon-bar'), CLASS='btn btn-navbar'), E.A('RUM Profile', CLASS='brand', href='#'), E.DIV(E.UL(E.LI(E.A('CPU time', href='cpu.html'), CLASS=cpu_class), E.LI(E.A('Wallclock time', href='wc.html'), CLASS=wc_class), E.LI(E.A('Help', href='help.html'), CLASS=help_class), CLASS='nav'), CLASS='nav-collapse collapse'), CLASS='container'), CLASS='navbar-inner'), CLASS='navbar navbar-inverse navbar-fixed-top'), E.BR(), E.BR(), E.BR(), E.DIV(contents, CLASS='container')))
def renew_board_cache(renew_cache_dict=True, renew_thread_cache=True, renew_style_cache=True): global board_cache#should be done by the request global board_cache_navigation global board_cache_main_page global style_cache global stats_cache = "" boards = sess.query(Board).filter().all()#add 'order by' if renew_cache_dict: board_cache = {} for b in boards: board_cache[b.address] = board_cache_class(b) if cf.static_board_footer: board_cache_navigation = cf.board_cache_footer else: board_cache_navigation = generate_navigation_board_list(boards) #there must be html code generated if cf.static_board_main_page: board_cache_main_page = cf.board_cache_main_page else: board_cache_main_page = generate_main_page_board_list(boards)#there must be html code generated start_stats_thread() if renew_style_cache: style_cache = [] for f in os.listdir('css'): fname, ext = os.path.splitext(f) if ext == '.css': style_cache.append(E.LINK(E.CLASS('stylesheetlink'), rel="alternate stylesheet", title=fname, href='/css/'+f, type="text/css"))
def password_change_menu(): html = E.HTML( E.HEAD( E.LINK(rel="stylesheet", href="/css/deeplight.css", type="text/css"), E.TITLE("Administration and moderation") ), E.BODY( E.H1(E.CLASS("heading"), "Farlight Engine Imageboard"), E.P(E.CLASS("loginmessage"), "Change your password"), E.FORM(E.CLASS("loginform"), E.INPUT(type = 'hidden', name = 'action', value = 'change'), E.INPUT(type = 'hidden', name = 'instance', value = 'password'), E.TABLE( E.TR(E.TD('OLD PASSWORD'), E.TD(E.INPUT(type = 'password', name = 'old_passwd', value = '')) ), E.TR(E.TD('NEW PASSWORD'), E.TD(E.INPUT(type = 'password', name = 'new_passwd', value = '')) ), E.TR(E.TD('NEW PASSWORD AGAIN'), E.TD(E.INPUT(type = 'password', name = 'new_passwd_again', value = '')) ), ), E.INPUT(type = 'submit', value = 'LOGIN'), method = 'POST', action = '/admin' ) ) ) return lxml.html.tostring(html)
def list_bans_menu(ban_list, purpose): """need to put bans and boards table creating to a joint function in future""" tablerows = [E.TR(E.TD(str(b.id)), E.TD(b.ip), E.TD(b.initiator), E.TD(time.strftime('%d/%m/%Y %H:%M', time.localtime(b.date))), E.TD(str(b.level)), E.TD(E.BUTTON('Снять', type = 'button', onclick = 'remove_ban(this);')) )for b in ban_list] #purpose will be applyed later html = E.HTML( E.HEAD( E.LINK(rel="stylesheet", href="/css/deeplight.css", type="text/css"), E.TITLE("Creating board"), E.SCRIPT(type = 'text/javascript', src = '/adminscript.js') #js ), E.BODY( E.DIV(E.CLASS('adminupdiv'), E.DIV(E.CLASS('logout'), E.A('Logout', href='/admin/logout')), E.H2(E.CLASS("heading"), "Listing bans"), ), E.TABLE( E.CLASS("boardstable"), E.TR(E.TH('ID'), E.TH('IP'), E.TH('Забанивший'), E.TH('Дата'), E.TH('Уровень'), E.TH('') ), *tablerows ) ) ) return lxml.html.tostring(html)
def login_page_gen(): html = E.HTML( E.HEAD( E.LINK(rel="stylesheet", href="/css/deeplight.css", type="text/css"), E.TITLE("Administration and moderation") ), E.BODY( E.H1(E.CLASS("heading"), "Farlight Engine Imageboard"), E.P(E.CLASS("loginmessage"), "You need to login"), E.FORM(E.CLASS("loginform"), E.TABLE( E.TR(E.TD('LOGIN'), E.TD(E.INPUT(type = 'text', name = 'login', value = '')) ), E.TR(E.TD('PASSWORD'), E.TD(E.INPUT(type = 'text', name = 'password', value = '')) ), ), E.INPUT(type = 'submit', value = 'LOGIN'), method = 'POST', action = '/admin/login' ) ) ) return lxml.html.tostring(html)
def __init__(self, datas, lang, freeze, title, css_path): super().__init__(datas, lang, freeze) self._html = builder.HTML( builder.HEAD( builder.META(charset="utf-8"), builder.TITLE(title), builder.LINK(rel="stylesheet", href=css_path), ), builder.BODY(builder.DIV(id="text_area")), )
def visit_Component(self, node): inst = getattr(self, 'inst', None) if inst: title = 'Instance {} of {} Register Map'.format(inst, node.name) else: title = 'Base {} Register Map'.format(node.name) self.title = title # Create the main content by sweeping the tree. bc = E.DIV(id='breadcrumbs') try: if self.breadcrumbs is not None: bc.append(self.breadcrumbs) except AttributeError: pass ww = node.width // 8 an = ((node.size - 1).bit_length() + 3) // 4 with self.tempvars(wordwidth=ww, address_nibbles=an, hlev=2): nodes = ([E.H1(title, id='title'), bc] + [E.P(d) for d in node.description] + [c for c in self.visitchildren(node)] + [self.footer(node)]) contentnode = E.DIV(*nodes, id='content') # Add a table of contents sidebar. We'll assume that everything that # wants to be in the TOC is already a heading and just work from there. h2list = E.UL() for elem in contentnode.iter('h2', 'h3'): id = escape(elem.text) elem.attrib['id'] = id if elem.tag == 'h2': h2node = E.LI(E.A(elem.text, href='#' + id)) h2list.append(h2node) h3list = None else: if h3list is None: h3list = E.UL() h2list.append(h3list) h3list.append(E.LI(E.A(elem.text, href='#' + id))) # Put it all together. return E.HTML( E.HEAD( E.TITLE(title), E.LINK(rel='stylesheet', type='text/css', href=htmlpathjoin(self.styledir, 'reg.css'))), E.BODY( E.DIV(E.DIV(E.P(E.A(title, href='#title')), h2list, id='sidebar'), contentnode, id='wrapper')), )
def make_head(): head = [ #builder.BASE(href="https://dakovalev1.github.io/my_site/"), #builder.BASE(href="http://localhost/my_site/docs/"), # ONLY FOR DEBUG!!! #builder.BASE(href=sys.argv[1]), builder.META(charset="utf-8"), builder.TITLE("Dmitry Kovalev"), builder.META(name="viewport", content="width=device-width, initial-scale=1"), builder.SCRIPT( "", type="text/javascript", src= "https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.4/MathJax.js", async="async"), builder.SCRIPT(open("src/js/mathjax.js").read(), type="text/x-mathjax-config"), builder.SCRIPT( "", src= "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" ), #builder.SCRIPT("", src="js/jquery.waypoints.min.js"), #builder.SCRIPT("", src="js/jquery.scrollTo.min.js"), builder.LINK( rel="stylesheet", href="https://use.fontawesome.com/releases/v5.8.1/css/all.css", integrity= "sha384-50oBUHEmvpQ+1lW4y57PTFmhCaXp0ML5d60M1M7uH2+nqUivzIebhndOJK28anvf", crossorigin="anonymous"), builder.LINK( rel="stylesheet", href= "https://cdn.rawgit.com/jpswalsh/academicons/master/css/academicons.min.css" ), builder.LINK(rel="stylesheet", href=base_url + "css/menu.css"), builder.LINK(rel="stylesheet", href=base_url + "css/common.css"), builder.SCRIPT("", src=base_url + "js/menu.js"), builder.SCRIPT("", src=base_url + "js/scroll.js"), ] return head
def _create_toc(self): # Add link for toc itself link = E.LINK(href='#rfc.toc') link.attrib["rel"] = 'Contents' self.buffers['toc_head_links'].append(self._serialize(link)) tocdepth = self.pis['tocdepth'] try: tocdepth = int(tocdepth) except ValueError: xml2rfc.log.warn('Invalid tocdepth specified, must be integer:', \ tocdepth) tocdepth = 3 curdepth = 1 for item in self._getTocIndex(): if item.level <= tocdepth: # set UL level if item.level > curdepth: self.buffers['toc_rows'].append('<ul>') for i in range(item.level, curdepth): self.buffers['toc_rows'].append('</ul>') curdepth = item.level # Create link for head link = E.LINK(href='#' + item.autoAnchor) link.attrib['rel'] = 'copyright' in item.autoAnchor and \ 'Copyright' or 'Chapter' if item.title and item.counter: link.attrib[ 'title'] = item.counter + ' ' + item.title.strip() self.buffers['toc_head_links'].append(self._serialize(link)) # Create actual toc list item a = E.A(item.title.strip(), href='#' + item.autoAnchor) counter_text = item.counter and item.counter + '. ' or '' # Prepend appendix at first level if item.level == 1 and item.appendix: counter_text = "Appendix " + counter_text li = E.LI(counter_text) li.append(a) self.buffers['toc_rows'].append(self._serialize(li)) for i in range(1, curdepth): self.buffers['toc_rows'].append('</ul>')
def gen_html(encoding=ENCODING): """Create the HTML structure :return: Return the body structure from lxml.html """ body = E.BODY() html = E.HTML( E.HEAD( E.LINK(rel="stylesheet", href=CSSFILE, type="text/css"), E.META(charset=encoding), ), body) return body
def board_creation_menu(): #here is the html board creation menu html = E.HTML( E.HEAD( E.LINK(rel="stylesheet", href="/css/deeplight.css", type="text/css"), E.TITLE("Creating board") ), E.BODY( E.DIV(E.CLASS('adminupdiv'), E.DIV(E.CLASS('logout'), E.A('Logout', href='/admin/logout')), E.H2(E.CLASS("heading"), "Create new board"), ), E.DIV(E.CLASS("boardcreateform"), E.FORM( E.INPUT(type = 'hidden', name = 'action', value = 'create'), E.INPUT(type = 'hidden', name = 'instance', value = 'board'), E.TABLE( E.TR(E.TD('Address'), E.TD(E.INPUT(type = 'text', name = 'address', value = '')) ), E.TR(E.TD('Tablename'), E.TD(E.INPUT(type = 'text', name = 'tablename', value = '')) ), E.TR(E.TD('Name'), E.TD(E.INPUT(type = 'text', name = 'name', value = '')) ), E.TR(E.TD('Fullname'), E.TD(E.INPUT(type = 'text', name = 'fullname', value = '')) ), E.TR(E.TD('Description'), E.TD(E.INPUT(type = 'text', name = 'description', value = '')) ), E.TR(E.TD('Pics number'), E.TD(E.INPUT(type = 'number', name = 'picsnum', value = '', min = '0', max = '10')) ), E.TR(E.TD('Bumplimit'), E.TD(E.INPUT(type = 'number', name = 'bumplimit', value = '', min = '0')) ), E.TR(E.TD('Max threads'), E.TD(E.INPUT(type = 'number', name = 'maxthreads', value = '', min = '-1')) ), E.TR(E.TD(E.INPUT(type='checkbox', name='delposts', value='1', checked='checked'), 'Удаление постов', colspan='2', style='text-align:center;')), E.TR(E.TD(E.INPUT(type='checkbox', name='delopposts', value='1', checked='checked'), 'Удаление тредов', colspan='2', style='text-align:center;')), ), E.INPUT(type = 'submit', value = 'Create'), method='POST', action='/admin/' ) ) ) ) return lxml.html.tostring(html)
def list_boards_menu(board_list, purpose): """need to put boards table creating to a separate function in future""" posts_num_cell = E.DIV(E.SPAN('????', style = 'display:inline-block; width:4em; text-align:center;'), E.INPUT(type='number', size='6', min='0', value='1', style = 'width: 6em;'), E.SELECT(E.OPTION('Секунды', value='1'), E.OPTION('Минуты', value='60'), E.OPTION('Часы', value='3600'), E.OPTION('Дни', value='86400', selected='') ), E.BUTTON('GET', onclick='get_posts_num_from_time(this)', type = 'button')) tablerows = [E.TR(E.TD(E.A(b.address, href = '/'+b.address)), E.TD(b.tablename), E.TD(str(b.name)), E.TD(str(b.fullname)), E.TD(str(b.description)), E.TD(str(b.category)), E.TD(str(b.pictures)), E.TD(str(b.bumplimit)), E.TD(str(b.maxthreads)), E.TD(copy.copy(posts_num_cell)) )for b in board_list] #purpose will be applyed later html = E.HTML( E.HEAD( E.LINK(rel="stylesheet", href="/css/deeplight.css", type="text/css"), E.TITLE("Creating board"), E.SCRIPT(type = 'text/javascript', src = '/adminscript.js') #js ), E.BODY( E.DIV(E.CLASS('adminupdiv'), E.DIV(E.CLASS('logout'), E.A('Logout', href='/admin/logout')), E.H2(E.CLASS("heading"), "Listing boards"), ), E.TABLE( E.CLASS("boardstable"), E.TR(E.TH('Адрес'), E.TH('Таблица'), E.TH('Название'), E.TH('Полное название'), E.TH('Описание'), E.TH('Категория'), E.TH('Максимум картинок'), E.TH('Бамплимит'), E.TH('Максимум тредов'), E.TH('Постов за последнее время') ), *tablerows ) ) ) return lxml.html.tostring(html)
def gen_index(p_list): about = html.fromstring(open("src/html/about.html").read()) contact = html.fromstring(open("src/html/contact.html").read()) index = builder.HTML( builder.HEAD( *make_head(), builder.LINK(rel="stylesheet", href=base_url + "css/about.css")), builder.BODY(make_menu(index=True), about, contact)) print(html.etree.tostring(index, pretty_print=True, method='html').decode("utf-8"), file=open(os.path.join(base_path, "index.html"), "w"))
def main(results_file): summary = {} with open(results_file, 'r') as f: summary = json.loads(f.read()) summary['directory'] = os.path.dirname(results_file) date = datetime.datetime.fromtimestamp( summary['timestamp']).strftime('%Y-%m-%d-%H:%M:%S') token_create_rps = summary['token_creation']['requests_per_second'] token_create_tps = summary['token_creation']['time_per_request'] token_validate_rps = summary['token_validation']['requests_per_second'] token_validate_tps = summary['token_validation']['time_per_request'] index = e.HTML( e.HEAD(e.LINK(rel='stylesheet', type='text/css', href='theme.css'), e.TITLE('OpenStack Keystone Performance')), e.BODY( e.DIV(e.H1('OpenStack Keystone Performance'), e.P('Published reports after each merged patch.', CLASS('subtitle')), id='header'), e.DIV( e.P('Last run date: ' + date, ), e.P( 'keystone SHA: ', e.A(summary['sha'], target='_blank', href=KEYSTONE_LINK + summary['sha'])), e.P( 'os_keystone SHA: ', e.A(summary['osa_sha'], target='_blank', href=OSA_LINK + summary['osa_sha'])), e.P(e.A('Performance Data', href=PERF_LINK, target='_blank')), e.DIV(CLASS('left'), e.H2('Create Token'), e.P(e.STRONG(token_create_rps), ' requests per second'), e.P(e.STRONG(token_create_tps), ' ms per request')), e.DIV( CLASS('right'), e.H2('Validate Token'), e.P(e.STRONG(token_validate_rps), ' requests per second'), e.P(e.STRONG(token_validate_tps), ' ms per request')), id='content'), e.DIV(e.P( 'Results provided by the ', e.A('OSIC Performance Bot', target='_blank', href=BOT_LINK)), id='footer'))) with open(os.path.join(summary['directory'], 'index.html'), 'w') as f: f.write(et.tostring(index))
def head(self): """The HEAD of the html document""" head = E.HEAD( E.META({ 'http-equiv': 'Content-Type', 'content': 'text/html; charset=utf-8' }), E.TITLE('%s -- GCC Python Plugin' % self.data['filename']), ) head.extend( E.LINK(rel='stylesheet', href=css + '.css', type='text/css') for css in ('extlib/reset-20110126', 'pygments_c', 'style')) head.extend( E.SCRIPT(src=js + '.js') for js in ('extlib/prefixfree-1.0.4.min', 'extlib/jquery-1.7.1.min', 'script')) return head
def visit_MemoryMap(self, node): """Create an HTML file for a MemoryMap.""" self.title = title = node.name + ' Peripheral Map' an = ((node.size - 1).bit_length() + 3) // 4 # Sweep the document tree to build up the main content with self.tempvars(wordwidth=1, address_nibbles=an, base=node.base, subdir=node.name + '_instances', hlev=2): children = list(self.visitchildren(node)) table = E.TABLE( E.TR(E.TH('Peripheral'), E.TH('Base Address'), E.TH('Size'), E.TH('Description'), *children), CLASS('component_list')) nodes = ([E.H1(title, id='title')] + [E.P(d) for d in node.description] + [E.HR(), table, self.footer(node)]) contentnode = E.DIV(*nodes, id='content') # Add a table of contents sidebar for each table row. instlist = E.UL() for elem in contentnode.xpath("//td[contains(@class, 'peripheral')]"): text = tostring(elem, method="text", encoding="unicode") id = escape(text) elem.attrib['id'] = id node = E.LI(E.A(text, href='#' + id)) instlist.append(node) # And put it all together. return E.HTML( E.HEAD( E.TITLE(title), E.LINK(rel='stylesheet', type='text/css', href=htmlpathjoin(self.styledir, 'reg.css'))), E.BODY( E.DIV(E.DIV(E.P(E.A(title, href='#title')), instlist, id='sidebar'), contentnode, id='wrapper')), )
def bootstrapify(self): """Add bootstrap cdn to headers of html""" if self.__htmltree is None: #raise Exception("HtmlTree has not been made yet") self.__make_tree() # add bootstrap cdn to head self.__htmltree.find('head').append( E.LINK(rel="stylesheet", href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css", type="text/css")) # center images for img_parent in self.__htmltree.xpath("//img/.."): # the space before the class to insert is CRITICAL! img_parent.attrib["class"] += " text-center" # make images responsive for img in self.__htmltree.xpath("//img"): # the space before the class to insert is CRITICAL! img.attrib["class"] += " img-responsive"
def main(): cursor = db.connect(user="******").cursor() query = db.Query("document d", "d.id", "d.title", "d.xml").order(2) query.join("doc_type t", "t.id = d.doc_type") query.where("t.name = 'Filter'") filters = [] for doc_id, doc_title, doc_xml in query.execute(cursor).fetchall(): filters.append(Filter(doc_id, doc_title, doc_xml)) tbody = builder.TBODY() caption = builder.CAPTION(TITLE) for name in sorted(Parameter.parameters, key=str.lower): parm = Parameter.parameters[name] parm.add_rows(tbody) page = builder.HTML( builder.HEAD( builder.TITLE(TITLE), builder.LINK(rel="stylesheet", href="/stylesheets/cdr.css"), builder.STYLE("th { text-align: right; vertical-align: top; }")), builder.BODY(builder.TABLE(caption, tbody), builder.CLASS("report"))) print("Content-type: text/html\n") print(etree.tostring(page, pretty_print=True).decode("ascii"))
def main_page_gen(): html = E.HTML( E.HEAD( E.LINK(rel="stylesheet", href="/css/deeplight.css", type="text/css"), E.TITLE("Administration and moderation") ), E.BODY( E.DIV( E.DIV(E.CLASS('logout'), E.A('Logout', href='/admin/logout')), E.H2(E.CLASS("heading"), "Admin menu"), ), E.P(E.CLASS("loginmessage"), "You are logged in"), E.DIV(E.CLASS('adminmainmenu'), E.A("create board", href = '?action=create&instance=board'), E.A("manage boards", href = '?action=list&list=boards&purpose=admin'), E.A("manage bans", href = '?action=list&list=bans&purpose=moderator'), E.A("manage users", href = '?action=list&list=users&purpose=admin'), E.A("change password", href = '?action=change&instance=password'), ) ) ) return lxml.html.tostring(html)
async def feeds_html(redis, lid): timeline = int(datetime.now().timestamp()) - fv.FEED_NEWS_TIMELINE df = await get_latest_news(redis, lid, top=fv.FEED_NEWS_TOP, timeline=timeline) html = E.HTML( E.HEAD( E.META(content='text/html', charset='utf-8'), E.LINK(rel='stylesheet', href='../css/style.css', type='text/css'), E.TITLE(E.CLASS('title'), f'{ct.GLOBAL_CHANNELS[lid]}实时新闻摘要'))) body = etree.SubElement(html, 'body') logger.debug( f'html: {lxml.html.tostring(html, pretty_print=True, encoding="utf-8").decode("utf-8")}' ) news_count = 0 for row in df.iterrows(): row = row[1] div = etree.SubElement(body, 'div') h1 = etree.SubElement(div, 'h1', attrib={'class': 'heading'}) a = etree.SubElement(h1, 'a', attrib={'href': row['url']}) a.text = row['title'] p1 = etree.SubElement(div, 'p', attrib={'class': 'time'}) p1.text = row['time'] p2 = etree.SubElement(div, 'p', attrib={'class': 'summary'}) p2.text = row['summary'] logger.debug( f'Append one news to html body, news: {etree.tostring(div, pretty_print=True, encoding="utf-8").decode("utf-8")}' ) news_count = news_count + 1 html_file = os.path.join(ct.DAT_DIR, f'{ct.GLOBAL_CHANNELS[lid]}.html') logger.info(f'Writing html to file: {html_file}, news count: {news_count}') with open(html_file, 'w', encoding='utf-8') as f: f.write( lxml.html.tostring(html, pretty_print=True, encoding='utf-8').decode('utf-8'))
def feeds_html(): for lid in ct.GLOBAL_CHANNELS: df = get_latest_news(lid) html = E.HTML( E.HEAD( E.META(content='text/html', charset='utf-8'), E.LINK(rel='stylesheet', href='../css/style.css', type='text/css'), E.TITLE(E.CLASS('title'), f'{ct.GLOBAL_CHANNELS[lid]}实时新闻摘要') ) ) body = etree.SubElement(html, 'body') for row in df.iterrows(): row = row[1] div = etree.SubElement(body, 'div') h1 = etree.SubElement(div, 'h1', attrib={'class': 'heading'}) a = etree.SubElement(h1, 'a', attrib={'href': row['url']}) a.text = row['title'] p1 = etree.SubElement(div, 'p', attrib={'class': 'time'}) p1.text = row['time'] p2 = etree.SubElement(div, 'p', attrib={'class': 'summary'}) p2.text = row['summary'] with open(os.path.join(ct.DAT_DIR, f'{ct.GLOBAL_CHANNELS[lid]}.html'), 'w', encoding='utf-8') as f: f.write(lxml.html.tostring(html, pretty_print=True, encoding='utf-8').decode('utf-8'))
def __init__(self, datas, title="", log_level="ERROR", css_path="css/styles.css", lang="fr", freeze=False): """ Initializing thanks to a JSON (datas) HTML document head and body created """ self.__lang = lang self.__freeze = freeze self.datas = datas self.log_level = log_level self.__sections = [] self._html = builder.HTML( builder.HEAD( builder.META(charset="utf-8"), builder.TITLE(title), builder.LINK(rel="stylesheet", href=css_path), ), builder.BODY(builder.DIV(id="text_area")), )
OiRA This parses the robot output.xml and produces an HTML file called oira-report.html """ from lxml import etree from lxml import html from lxml.html import builder as E # A plain template with Bootstrap report = E.HTML( E.HEAD( E.LINK( href=("http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/" "bootstrap-combined.min.css"), rel="stylesheet", ), E.TITLE("OiRA Testing Report"), E.META(name="viewport", content="width=device-width, initial-scale=1.0"), ), E.BODY( E.DIV( E.CLASS("container"), E.DIV(E.CLASS("page-header"), E.H1("OiRA Testing Report")), id="content-area", )), )
termin["name"] = aktuelle_veranstaltung termin["modul"] = modulname termin["studiengang"] = studiengaenge[counter] termin["id"] = id id += 1 tabelle.append(termin) #if "s_termin_typ" in termin: # print(" " + termin["s_termin_typ"]) # print(" " + termin["s_termin_von"] + " - " + termin["s_termin_bis"]) counter += 1 # Alle Module eingeladen, hoffe ich htmlfile = E.HTML( E.HEAD(E.LINK(rel="stylesheet", href="plan.css", type="text/css"), E.SCRIPT(src="plan.js", type="text/javascript"), E.META(charset="utf-8"), E.TITLE("Test")), E.BODY(E.H1("Stundenplan"))) document = htmlfile.find("body") for studiengang in studiengaenge: print(studiengang) document.append(E.H2(studiengang, name=studiengang)) container = E.DIV(E.CLASS("plancontainer")) # E.DIV(E.CLASS("plancontainer")) for stunde in range(59): style = "top: " + str(2 + (100 / 60) * stunde) + "%; " mnt = str(int((stunde + 2) % 4 * 15)) if mnt == "0":
import scraperwiki # Blank Python print "Hello, Winnipeg crime!" import scraperwiki html = scraperwiki.scrape("http://www.winnipeg.ca/police/press/2012/01jan/2012_01_31.stm") print html import lxml.html root = lxml.html.fromstring(html) from lxml.html import builder as E from lxml.html import usedoctest html = E.HTML( E.HEAD( E.LINK(rel="stylesheet", href="great.css", type="text/css"), E.TITLE("Best Page Ever") E.BODY( E.H1(E.CLASS("heading"), "Top News"), E.P("World News only on this page", style="font-size: 200%"), "Ah, and here's some more text, by the way.", lxml.html.fromstring("<p>... and this is a parsed fragment ...</p>") ..) ..) >>> print lxml.html.tostring(html) <html> <head> <link href="great.css" rel="stylesheet" type="text/css"> <title>Best Page Ever</title> </head> <body> <h1 class="heading">Top News</h1>
def build(input_file, configs): # Making build folder build_name = os.path.normpath(configs["buildPath"] + configs["timeStamp"]) base_dir = os.path.abspath(os.path.dirname(input_file)) build_dir = os.path.join(base_dir, build_name) os.makedirs(build_dir, exist_ok=True) # Getting list of excluded files: excludes = get_files(base_dir, configs["exclude"]) # Merging requested files in config-file: merged_objects = merge(configs["merge"], base_dir, build_dir, excludes, configs["obfuscate"]) merged_files = [f for mo in merged_objects for f in mo.merging_files] # Traverse directory of the given html file recursively and process unmerged remaining files: for root, dirs, files in os.walk(base_dir): if build_name in dirs: dirs.remove(build_name) if files: # remove config file from files list: if configs["file"] in files: files.remove(configs["file"]) dest = os.path.join(build_dir, os.path.relpath(root, base_dir)) for file in files: file_path = os.path.join(root, file) # If file was already part of a merge process: if file_path in merged_files or file_path in excludes: continue if is_min_file_exists(file, file_path): continue os.makedirs(dest, exist_ok=True) ext = os.path.splitext(file)[1][1:] if ext in configs["minify"] and not is_min_file(file): # Processing(minifying) js/css file: print("minifying %s" % file_path) min_file_path = os.path.join(dest, os.path.splitext(os.path.basename(file))[0] + ".min." + ext) if ext == "js": data = slimit.minify(open(file_path, "r", encoding="utf-8").read(), mangle=configs["obfuscate"], mangle_toplevel=False) else: data = csscompressor.compress(open(file_path, "r", encoding="utf-8").read()) with open(min_file_path, "w", encoding="utf-8") as min_file: min_file.write(data) else: # just copy the file. print("copying %s" % file_path) shutil.copy2(file_path, dest) # Now editing given html file <script> and <link> tags: print("Updating html file...") tree = None with open(os.path.join(build_dir, os.path.basename(input_file)), "r", encoding="utf-8") as html_file: tree = html.parse(html_file) # Updating javascript tags: for tag in tree.findall("//script[@src]"): if tag.attrib["src"].startswith("http"): continue # Get the complete path of source file: src_file = os.path.normpath(os.path.join(base_dir, tag.attrib["src"])) if src_file in merged_files: # Source file is part of a merge: mo = get_merge_object(merged_objects, src_file) if mo is not None and not mo.added: # Replacing new merged file tag with old one: new_tag = E.SCRIPT(type="text/javascript", src=mo.into) tag.getparent().replace(tag, new_tag) mo.added = True else: # Merged file tag was already added. tag.getparent().remove(tag) elif not src_file.endswith(".min.js"): # replacing source file with minified one: tag.attrib["src"] = os.path.relpath(src_file, base_dir)[:-2] + "min.js" # Updating stylesheet link tags: for tag in tree.xpath('//*[@rel="stylesheet" or @media="all" or @media="screen"]'): if tag.attrib["href"].startswith("http"): continue # Get the complete path of source file: href_file = os.path.normpath(os.path.join(base_dir, tag.attrib["href"])) if href_file in merged_files: # Source file is part of a merge: mo = get_merge_object(merged_objects, href_file) if mo is not None and not mo.added: # Replacing new merged file tag with old one: new_tag = E.LINK(rel="stylesheet", type="text/css", href=mo.into) tag.getparent().replace(tag, new_tag) mo.added = True else: # Merged file tag was already added. tag.getparent().remove(tag) elif not href_file.endswith(".min.css"): # replacing href file with minified one: tag.attrib["href"] = os.path.relpath(href_file, base_dir)[:-3] + "min.css" with open(os.path.join(build_dir, os.path.basename(input_file)), "wb") as html_file: html_file.write(html.tostring(tree, encoding="utf-8", pretty_print=True)) print("Done!")