is it possible to write in to the page content from within a python code block in a Bottle SimpleTemplate file?
e.g.:
<!DOCTYPE html>
<html lang="en">
<body>
<%
# A block of python code
basket = [1,2,3]
print("<ul>") # this prints on the server console, not the rendered page
for item in basket:
print("<li>" + str(item) + "</li>")
print("</ul>")
%>
</body>
</html>
I know i could use the specific syntax for loops in this case, but i'd like to know an alternative for use in more complex cases:
<ul>
% for item in basket:
<li>{{item}}</li>
% end
</ul>
<!DOCTYPE html>
<html lang="en">
%result = ''
<body>
<%
# A block of python code
basket = [1,2,3]
result+="<ul>" # this prints on the server console, not the rendered page
for item in basket:
result+="<li>" + str(item) + "</li>"
result+="</ul>"
%>
{{result}}
</body>
</html>
No, I'm afraid it's not directly possible. And even if it were, you probably shouldn't do it.
The cleanest designs keep their logic in the server code; templates are merely for presentation.
For example, this templating tutorial says:
In general we'd like to separate the HTML content from the program logic.
You said:
I know i could use the specific syntax for loops in this case, but i'd like to know an alternative for use in more complex cases
I'm curious: why are you looking for an alternative? You allude to "more complex cases," but your example is just a loop. If you show us an example which you think can't be handled cleanly the standard way, perhaps we can help you with that specific case.
Related
This question already has answers here:
In Playwright for Python, how do I retrieve a handle for elements from within an frame (iframe)?
(3 answers)
Closed yesterday.
I need to extract the text from the second doctype using playwright (mostly) or another tool. (python only)
Can anyone help?
<!DOCTYPE html>
<html data-lang-tag="" lang="ru">
<head>
`v`<body class='webp'
`v`<div id="app">
`v`<div id="main-container" class>
`v`<main class="content-wrapper">
`v`<main class="main">
`v`<div data-v-c735354e class="....">
`v`#document
<!DOCTYPE html>
`v` <html data-lang-tag="" lang="ru">
`**HERE is what I need - text**`
</iframe>
</div>
</....>
</....>
With the help of conventional locators, this cannot be done, perhaps someone faced such a task?
When I search for "frame.content()"
The following doctype doesn't seem to exist...
it is necessary to search through
frame_locator.frame_locator(selector)
in my example it looks like this:
page.frame_locator("iframe").locator(".sc-iAEawV > .sc-gikAfH > .sc-iJnaPW")
I'm using Selenium for functional testing of a Django application and thought I'd try html5lib as a way of validating the html output. One of the validations is that the page starts with a <!DOCTYPE ...> tag.
The unit test checks with response.content.decode() all worked fine, correctly flagging errors, but I found that Selenium driver.page_source output starts with an html tag. I have double-checked that I'm using the correct template by modifying the title and making sure that the change is reflected in the page_source. There is also a missing newline and indentation between the <html> tag and the <title> tag.
This is what the first few lines looks like in the Firefox browser.
<!DOCTYPE html>
<html>
<head>
<title>NetLog</title>
</head>
Here's the Python code.
self.driver.get(f"{self.live_server_url}/netlog/")
print(self.driver.page_source
And here's the first few lines of the print when run under the Firefox web driver.
<html><head>
<title>NetLog</title>
</head>
The page body looks fine, while the missing newline is also present between </body> and </html>. Is this expected behaviour? I suppose I could just stuff the DOCTYPE tag in front of the string as a workaround but would prefer to have it behave as intended.
Chris
Im trying to get xpath from text instead of a URL. But i keep getting the error "AttributeError: 'HtmlElement' object has no attribute 'XPath'"
see code below.
from lxml import html
var ='''<html lang="en">
<head>
<title>Selecting content on a web page with XPath</title>
</head>
<body>
This is the body
</body>
</html>
'''
tree = html.fromstring(var)
body = tree.XPath('//*/body')
print(body)
It has been 15 years since I last used Python, but as far as I can tell, it is a case-sensitive language, and the xpath method is all lowercase.
So try this:
body = tree.xpath('//*/body')
I am trying to send an email using sendgrid. For this I created an html file and I want to format some variables into it.
Very basic test.html example:
<html>
<head>
</head>
<body>
Hello World, {name}!
</body>
</html>
Now in my Python code I am trying to do something like this:
html = open("test.html", "r")
text = html.read()
msg = MIMEText(text, "html")
msg['name'] = 'Boris'
and then proceed to send the email
Sadly, this does not seem to be working. Any way to make this work?
There are a few ways to approach this depending on how dynamic this must be and how many elements you are going to need to insert. If it is one single value name then #furas is correct and you can simply put
html = open("test.html", "r")
text = html.read().format(name="skeletor")
print(text)
And get:
<html>
<head>
</head>
<body>
Hello World, skeletor!
</body>
</html>
Alternatively you can use Jinja2 templates.
import jinja2
html = open("test.html", "r")
text = html.read()
t = jinja2.Template(text)
print(t.render(name="Skeletor"))
Helpful links: Jinja website
Real Python Primer on Jinja
Python Programming Jinja
This question already has answers here:
How to get path of an element in lxml?
(4 answers)
Closed 4 years ago.
Is there a way to show:
(a) the full path to a located node?
(b) show the attributes of the path nodes even if I don't know what those attributes might be called?
For example, given a page:
<!DOCTYPE html>
<HTML lang="en">
<HEAD>
<META name="generator" content=
"HTML Tidy for HTML5 for Linux version 5.2.0">
<META charset="utf-8">
<TITLE>blah ombid lipsum</TITLE>
</HEAD>
<BODY>
<P>I'm the expected content</P>
<DIV unexpectedattribute="very unexpected">
<P>I'm wanted but not where you thought I'd be</P>
<P class="strangeParagraphType">I'm also wanted text but also mislocated</P>
</DIV>
</BODY>
</HTML>
I can find wanted text with
# Import Python libraries
import sys
from lxml import html
page = open( 'findme.html' ).read()
tree = html.fromstring(page)
wantedText = tree.xpath(
'//*[contains(text(),"wanted text")]' )
print( len( wantedText ), ' item(s) of wanted text found')
Having found it, however, I'd like to be able to print out the fact that the wanted text is located at:
/HTML/BODY/DIV/P ... or, even better, to show that it is located at /HTML/BODY/DIV/P[2]
... and much better, to show that it is located at that location with /DIV having unexpectedattribute="very unexpected" and the final <P> having the class of strangeParagraphType.
Could use something like this for the first example you have:
['/'.join(list([wt.tag] + [ancestor.tag for ancestor in wt.iterancestors()])[::-1]).upper() for wt in wantedText]
Third one can be created using the attrib property on the element objects and some custom logic:
wantedText[0].getparent().attrib
>>> {'unexpectedattribute': 'very unexpected'}
wantedText[0].attrib
>>> {'class': 'strangeParagraphType'}
Edit: Duplicate answer link up top is definitely a better way to go.