Capture a code block into a string variable in python - python

I want to dynamically create an html code block but I'm not sure how to assign this into a variable:
<head>
<style>
body {
border-style: solid;
border-width: 5px;
border-color: green;
border-radius: 5px;
border-spacing: 30px;
background-color: #FFFFC2;
padding-bottom: 5px;
font-size: 25px;
}
li {
color: #F7270F;
font-weight: bold;
}
</style>
</head>
<body>
<div style="margin-bottom: 5px; margin-top: 5px; margin-left: 10px; margin-right: 10px;">
<h1 align="center">Auctions for Week of 08-01-2018</h1>
<p>You are bidding on the following item:</p>
<ul><li>This is the item for sale</li></ul>
<p>Condition is pack fresh unless otherwise indicated. Please review the pictures carefully and if you have any questions about something specific, ask.</p>
<p><b>Shipping:</b> Shipping will be calculated based on buyer location. No premiums are charged. Cards are mailed in an 8x5 bubble mailer and shipped First Class mail unless the price exceeds $50, at which point they will be shipped Priority at no additional cost to the buyer. If you win multiple auctions, please wait for an invoice to be sent.</p>
</div>
</body>
I've tried executing:
html_desc="<code_block>"
but it doesn't like the way that works... so I'm a bit stumped. The reason I'm trying to put this into a variable is because I need to make this a key value for a JSON statement.

You can put that code block inside triple quotes """ (I put the variable inside json.dumps, just for example):
from pprint import pprint
import json
html_desc = """<head>
<style>
body {
border-style: solid;
border-width: 5px;
border-color: green;
border-radius: 5px;
border-spacing: 30px;
background-color: #FFFFC2;
padding-bottom: 5px;
font-size: 25px;
}
li {
color: #F7270F;
font-weight: bold;
}
</style>
</head>
<body>
<div style="margin-bottom: 5px; margin-top: 5px; margin-left: 10px; margin-right: 10px;">
<h1 align="center">Auctions for Week of 08-01-2018</h1>
<p>You are bidding on the following item:</p>
<ul><li>This is the item for sale</li></ul>
<p>Condition is pack fresh unless otherwise indicated. Please review the pictures carefully and if you have any questions about something specific, ask.</p>
<p><b>Shipping:</b> Shipping will be calculated based on buyer location. No premiums are charged. Cards are mailed in an 8x5 bubble mailer and shipped First Class mail unless the price exceeds $50, at which point they will be shipped Priority at no additional cost to the buyer. If you win multiple auctions, please wait for an invoice to be sent.</p>
</div>
</body>"""
pprint(json.dumps({html_desc: "Some Value"}))

Related

Copying hyperlinked text to the clipboard in Python pyperclip3

My program needs to copy into the clipboard some text with hyhperlinks, so that the user can later paste the text (with hyperlinks) into an app (e.g. Word, Slack).
This functionality works in most apps: for example if I copy a piece of text from a browser (or a Word doc, or a Slack message) which contains hyperlinks, when I paste it into another app it preserves the links.
However when I paste this content with pyperclip I only recover the text (there are no hyperlinks).
After some research I think I need to use a binary form of paperclip content, via pyperclip3. But I don't know how to construct the hyperlinked string object.
When I pyperclip3.paste() after copying the string from Word, I obtain what looks like a binary PDF object. Perhaps I need to create a binary PDF with the link and pass it to pyperclip3.copy()? Are there easier ways? Perhaps MIME?
Not sure if it is possible, but it's going to be very hard to use pyperclip to get hyperlinks, maybe even impossible. A possible option is to use Beautiful Soup and richxerox using Mac environment:
from richxerox import *
from bs4 import BeautifulSoup
soup = BeautifulSoup(pasteboard.get_contents(format='html'),'lxml')
links = [i.attrs['href'] for i in soup.find_all('a')]
print(links)
When copying to the clipboard in Windows, the application can choose to make several formats of the data available to an application that wishes to paste the data. I have attached a screenshot of the different formats available when copying from Chrome.
I know PySide6, a Python wrapper around Qt, lets you give the mime-type of the data you are putting into the clipboard. I don't know if there is a similar feature in pyperclip. This feature lets you share html with included hyperlinks directly with another application.
app.clipboard().mimeData().setHtml("""<html>
<body>
<!--StartFragment--><h3 class="s-post-summary--content-title" style="margin: -0.15rem 0px 0.3846rem; padding-top: 0px; padding-right: var(--su24); padding-bottom: 0px; padding-left: 0px; border: 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-variant-numeric: inherit; font-variant-east-asian: inherit; font-weight: 400; font-stretch: inherit; line-height: var(--lh-md); font-family: -apple-system, BlinkMacSystemFont, "Segoe UI Adjusted", "Segoe UI", "Liberation Sans", sans-serif; font-size: var(--fs-body3); vertical-align: baseline; box-sizing: inherit; display: block; word-break: break-word !important; overflow-wrap: break-word !important; hyphens: auto !important; color: rgb(35, 38, 41); letter-spacing: normal; orphans: 2; text-align: left; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">
Copying hyperlinked text to the clipboard in Python pyperclip3</h3><div class="s-post-summary--content-excerpt" style="margin-top: calc(var(--su2) * -1); margin-right: 0px; margin-bottom: var(--su8); margin-left: 0px; padding: 0px; border: 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-variant-numeric: inherit; font-variant-east-asian: inherit; font-weight: 400; font-stretch: inherit; line-height: inherit; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI Adjusted", "Segoe UI", "Liberation Sans", sans-serif; font-size: 13px; vertical-align: baseline; box-sizing: inherit; color: var(--fc-medium); display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; word-break: break-word !important; overflow-wrap: break-word !important; hyphens: auto !important; letter-spacing: normal; orphans: 2; text-align: left; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">
My program needs to copy into the clipboard some text with hyhperlinks, so that the user</div><!--EndFragment-->
</body>
</html>
""")
Update: Pyperclip "Currently only handles plaintext." So copying hyperlinks isn't an option currently with pyperclip. https://github.com/asweigart/pyperclip#:~:text=Currently%20only%20handles%20plaintext.

List not available after clicking on a button while trying to build a REST-API using Flask, Python and Postgresql

I am trying to build a web-app which extracts and inputs information about different city buildings using Python, Flask and HTML. At the moment I want to create a button which after clicking it will give me a list of all the buildings available on the database. The database is populated and stored in PostgreSQL. The problem is that the button is created and displayed but the list is not. I used the second answer on this link as a reference.
My Python code looks like as follows :
app = flask.Flask(__name__)
#app.route('/')
def home():
return flask.render_template('interface.html')
#app.route('/GetBuildingsLists', methods = ['GET','POST'])
def GetBuildingsLists():
print('Connecting to the PostgreSQL database...')
db = pg.connect(
host="****",
database="****",
user ="****",
password="*****")
db_cursor = db.cursor()
print('PostgreSQL database version:')
db_cursor.execute('SELECT version()')
q = ("SELECT building_id FROM table1")
db_cursor.execute(q)
buildings = db_cursor.fetchall()
unique_buildings = list(dict.fromkeys(buildings))
db_cursor.close()
#print(unique_buildings)
return flask.render_template('interfaceLists.html', unique_buildings = unique_buildings)
if __name__ == '__main__':
app.run()
Meanwhile, on a template folder I have interfaceLists.html as below :
<html>
<head>
<title>Results</title>
<style>
.links-unordered {
display: inline-block;
position: relative;
}
.links-unordered {
margin-top: 20px;
min-height: 30px;
}
.links-unordered .toggle-button {
text-decoration: none;
padding: 12px 16px 12px 16px;
transition: 0.2s;
border: 1px solid black;
}
.links-unordered .toggle-button:hover,
.links-unordered .toggle-button:active,
.links-unordered .toggle-button:focus,
.links-unordered .toggle-button:visited {
text-decoration: none;
color: black;
}
.links-unordered .toggle-button:hover {
border-width: 2px;
}
.links-unordered ul {
position: absolute;
top: 10px;
margin-top: 25px;
padding-inline-start: 20px;
}
.links-unordered ul li {
line-height: 25px;
padding-left: 15px;
}
.links-unordered a {
text-decoration: none;
color: black;
}
</style>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="demo_script_src.js"></script>
<div class="links-unordered">
<a class="toggle-button" href="#">Buildings</a>
{% for building in unique_buildings %}
<ul style="display:none;">
<li>building[0]</li>
</ul>
{% endfor %}
</div>
</body>
</html>
I take the results from the PostgreSQL using a query in the python code and store them in the list called unique_buildings. I have tried to display afterwards the results as an unordered list but the list is not displayed.
The .js file mention in the HTML file performs the animation while using the button and it looks like this :
$(document).ready(function() {
$(".toggle-button").click(function() {
$(this).parent().find("ul").slideToggle(function() {
// Animation complete.
});
});
})
Can someone please help me by telling what might be wrong with my script and why what I want is not working? Thank you!!

CSS only partially rendering when using HTML with Flask?

I've been using Python and Flask to host a webpage, which renders data from HTML. The Python code runs well, and is able to load the routes/webpages I'm targeting. However, my HTML page only seems to partially apply the Stylesheet.
However, when I render the page, it only seems to render the styling for the Nav Bar (TopNav class).
I've tried a few things, such as using IDs, creating new classes and adding to a div, using code from W3 to prevent typos, and even creating a new test html document with the same stylesheet. However, I still seem to be having the same issue.
What I'd like the stylesheet to do is provide a background color for the button, display it (along with ~20 total buttons) in a grid-like manner, and use a different background image for each button. I also played with the idea of adding the images using in-line styles, but that didn't help either.
Here's a snippet of the code:
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='Styles.css') }}">
</head>
<body>
<div class="topnav">
Home
Standings
Results
<a class="active" href="/teams">Teams</a>
Contact
</div>
<div class="team-buttons">
<button type="button" class="team-button">Text</button>
<button type="button" class="team-button" id='Wolves' >Text</button>
</div>
</body>
</html>
And the CSS
/* Add a black background color to the top navigation */
.topnav {
background-color: #333;
overflow: hidden;
}
/* Style the links inside the navigation bar */
.topnav a {
float: left;
color: #f2f2f2;
text-align: center;
padding: 14px 16px;
text-decoration: none;
font-size: 17px;
}
/* Change the color of links on hover */
.topnav a:hover {
background-color: #ddd;
color: black;
}
/* Add a color to the active/current link */
.topnav a.active {
background-color: #4CAF50;
color: white;
}
.team-buttons button {
background-color: #4CAF50;
border: 1px solid green;
color: white;
padding: 10px 24px;
cursor: pointer;
width: 50%;
display: block;
}
.team-buttons button:not(:last-child) {
border-bottom: none;
}
.team-buttons button:hover {
background-color: #3e8e41;
}
.team-button {
background-color: #ef4242;
overflow: hidden;
border: 0;
background-size: 100%;
}
.team-button a {
float: left;
color: #070000;
text-align: center;
padding: 10px 12px;
text-decoration: none;
font-size: 15px;
}
#wolves{
background-color: #4CAF50;
background-image: url('https://images.racingpost.com/football/teambadges/2848.png');
cursor:pointer;
border:none;
width:100px;
height:100px;
}
Apologies if I've missed something obvious, but I've been looking through this for a few hours now and still not found what the issue might be. Insight into this would be helpful.
Resolved this.
I think the issue I was running into was that the webpage was pulling data from the cache. As the .topnav had been added earlier, that was loaded into the style sheet, however, the newer classes weren't being added.
Found this by right-clicking and going to View Page Source.
Simple fix for this would be clearing cache, or Ctrl + Shift + R (to force a reload)

How to find element by long complicated xpath?

I want to find a button, but don't know how as the html code is complicated. Can you help me?
HTML
<div style="margin-top: 20px;">
<span style="display: inline-block; margin: 5px; padding: 10px 15px; border-radius: 5px; font-size: 18px; line-height: 16px; cursor: pointer; color: rgb(255, 255, 255); background-color: rgb(99, 99, 102);">Bugsnag akzeptieren
</span>
<span style="display: inline-block; margin: 5px; padding: 10px 15px; border-radius: 5px; font-size: 18px; line-height: 16px; cursor: pointer; color: rgb(255, 255, 255); background-color: rgb(0, 122, 255);">Alle akzeptieren
</span>
</div>
So I want to find the second element and tried things like:
self.browser.find_elements_by_xpath("//span[#style='the whole text that equals style in the html']")
But it does not seem to work...
Depending on what you would like to do with it, you could do //span[2] to select the second span:
Example of Selecting Element
self.browser.find_elements_by_xpath("//span[2]")
if you want the entire element.
Example of Selecting Text
self.browser.find_elements_by_xpath("//span[2]/text()")
if you want the inner html text of the second span.
I tested the xpath expression on this website to make sure that it works.
I copied in the html you provided and just entered the xpath expression //span[2]/text() to test it.
More info on xpath here.

Using HTML forms input for python code and getting output back in HTML webpage

I´ve been looking for answers and just lost the sight in all the different ones here.
I am bulding a tool, where you can enter a funding ID (included in papers) and a python code collects different papers from different websites and gives them a score in relevance.
My problem: I built a website with html/css and now I want to use the entered funding ID in one of the forms to pass it on to my python program. I know that i can use action in the form in my html to connect my html file with a different file. I read a lot of things about CGI and servers and Apache, etc. others talked about flask. I just want to find a simple way to exchange information from my html file and my python code and how can I display the information I got from my code in an HTML website?
Thank you!
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {
font-family: "Verdana", sans-serif;
}
.header {
padding: 60px;
text-align: center;
background: #0C0040;
color: white;
font-size: 30px;
}
.text_header {
margin-left: 160px;
letter-spacing: 6px;
}
.sub_header {
color: #00BFFF;
letter-spacing: 4px;
}
.sidenav {
height: 100%;
width: 160px;
position: fixed;
z-index: 1;
top: 0;
left: 0;
background-color: #474e5d;
overflow-x: hidden;
padding-top: 20px;
}
.sidenav a {
padding: 6px 8px 6px 16px;
text-decoration: none;
font-size: 25px;
color: #00BFFF;
display: block;
}
.sidenav a:hover {
color: #f1f1f1;
}
.main {
margin-left: 160px; /* Same as the width of the sidenav */
font-size: 28px; /* Increased text to enable scrolling */
padding: 0px 10px;
text-align: center;
}
.title{
color: #0C0040
text-align: center;
}
#media screen and (max-height: 450px) {
.sidenav {padding-top: 15px;}
.sidenav a {font-size: 18px;}
}
</style>
</head>
<body>
<div class="header">
<div class="text_header">
<h1>Looking for more?</h1>
<div class="sub_header">
<p>find equally relevant papers from the same funder</p>
</div>
</div>
</div>
<!--- so far only the About Us page is linked --->
<div class="sidenav">
About Us
Services
Contact
</div>
<div class="main">
<div class="title"> <h2>Insert your funding ID here:</h2></div>
<!--- this is the form where the input is put in--->
<div class="input">
<form name="search" action="../Python/example.py" method="post">
<label for="input">enter in correct format:</label>
<input type="text" name="input" id="input">
<input type="submit" value="Submit">
</form>
</div>
</div>
</body>
</html>
WARNING: This is only for amusement purposes--do not use in production.
Sticking to the Python standard library, here's an example to get you started.
from http.server import BaseHTTPRequestHandler, HTTPServer
class WebServer(BaseHTTPRequestHandler):
def do_POST(self):
content_length = int(self.headers['Content-Length'])
funding_id = bytes.decode(self.rfile.read(content_length)).split('input=')[1]
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write(bytes(f'<html><head><title>Funding ID Form Submit</title></head><body><p><b>Funding ID:</b> {funding_id}</p></body></html>', "utf-8"))
ws = HTTPServer(('localhost', 8080), WebServer)
ws.serve_forever()
You will need to change the action attribute of your HTML <form> to action="http://localhost:8080/" to see this in action.
Similarly, you can serve normal page requests by implementing the do_GET method for the WebServer class.
As already stated, this is for amusement/learning purposes. If you're putting something into production, look into learning something like Flask or Django

Categories