How to use a Python Variable in HTML code? - python

I have a String variable(name) that contains the name of the song.
(Python)
from pytube import YouTube
yt = YouTube("https://www.youtube.com/watch?v=6BYIKEH0RCQ")
name = yt.title #Contains the title of the song
Here is my HTML code for website to download the mp3 song:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Download</title>
</head>
<body>
<button>Click here </button>
</body>
</html>
With this code, I'd like to use the exact title of song as the name of the file when its been downloaded from the user.
I want to use the name Variable from Python in place of Song_name in HTML code.
Please suggest me any possible way in order to make this work.

You can try try this:
from pytube import YouTube
yt = YouTube("https://www.youtube.com/watch?v=6BYIKEH0RCQ")
name = yt.title
HTML=f"""
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Download</title>
</head>
<body>
<button>Click here </button>
</body>
</html>
"""
with open("test.html","w") as f:
f.write(HTML)
This will put title of song in download attribute. If you want you may put it anywhere. Just don't forget to use f"" and {variable}.

Related

Not getting data from request in python

I was trying to fetch a product info from an online store. It doesn't require any kind of authentication. I can see product information from the browser. I've inspected in developer tools and found the request which fetches data from the URL. My python code is bellow
import requests
def coles():
URL = "https://shop.coles.com.au/search/resources/store/20520/productview/bySeoUrlKeyword/mutti-tomato-passata-2349503p"
PARAMS = {
"catalogId": 12064
}
res = requests.get(URL,PARAMS)
print(res.text)
#coles()
if __name__ == '__main__':
coles()
But I'm getting this instead of the product info
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="shortcut icon" href="about:blank">
</head>
<body>
<script src="/149e9513-01fa-4fb0-aad4-566afd725d1b/2d206a39-8ed7-437e-a3be-862e0f06eea3/j.js"></script>
<script src="/149e9513-01fa-4fb0-aad4-566afd725d1b/2d206a39-8ed7-437e-a3be-862e0f06eea3/f.js"></script>
<script src="/149e9513-01fa-4fb0-aad4-566afd725d1b/2d206a39-8ed7-437e-a3be-862e0f06eea3/fingerprint/script/kpf.js?url=/149e9513-01fa-4fb0-aad4-566afd725d1b/2d206a39-8ed7-437e-a3be-862e0f06eea3/fingerprint&token=dcc221cb-d87a-e9e3-5316-7c7a20910bf8"></script>
</body>
</html>
But in the inspection, I got something like this. Maybe I need to add some header information or missing something.
Here is request info and paramerter
If I put this request URL in browser I get the data.

Switch all "href = (link)" with "onclick = (PythonScript(link)) "

I am working on a webscraper that scrapes a website, does some stuff to the body of the website, and outputs that into a new html file. One of the features would be to take any hyperlinks in the html file and instead run a script where the link would be an input for the script.
I want to go from this..
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Scraper</title>
</head>
<body>
<a href="/wiki/Mercury_poisoning" title="Mercury poisoning">
mercury poisoning
</a>
</body>
</html>
To this....
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Scraper</title>
</head>
<body>
<a onclick ='pythonScript(/wiki/Mercury_poisoning)' href="#" title="Mercury poisoning">
mercury poisoning
</a>
</body>
</html>
I did a lot of googling and I read about jQuery and ajax but do not know these tools and would prefer to do this in python. Is it possible to do this using File IO in python?
You can do something like this using BeautifulSoup:
PS: You need to install Beautifulsoup: pip install bs4
from bs4 import BeautifulSoup as bs
html = '''<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Scraper</title>
</head>
<body>
<a href="/wiki/Mercury_poisoning" title="Mercury poisoning">
mercury poisoning
</a>
</body>
</html>
'''
soup = bs(html, 'html.parser')
links = soup.find_all('a')
for link in links:
actual_link = link['href']
link['href'] = '#'
link['onclick'] = 'pythonScript({})'.format(actual_link)
print(soup)
Output:
<html>
<head>
<meta charset="utf-8"/>
<title>Scraper</title>
</head>
<body>
<a href="#" onclick="pythonScript(/wiki/Mercury_poisoning)" title="Mercury poisoning">
mercury poisoning
</a>
</body>
</html>
Bonus:
You can also create a new HTML file like this:
with open('new_html_file.html', 'w') as out:
out.write(str(soup))

Jinja2/Python insert a image(s) into html

I am just looking into using Jinja2 with a python application I have already written. I may be going about this in the wrong way, but here is what I would like to do.
from jinja2 import Environment, FileSystemLoader
from weasyprint import HTML
env = Environment(loader=FileSystemLoader('.'))
template = env.get_template("really.html")
template_vars = {"title":"TITLE","graph":'total.png'}
html_out = template.render(template_vars)
HTML(string=html_out).write_pdf("report.pdf")
This nearly produces what I want, I get a pdf called report.pdf, but instead of the attached file, it is a string of total.png. This is my first run at using Jinja, so hopefully attaching an image like this is possible. Thanks.
This is the template, not much built, just trying to do this piece at first.
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>{{ title }}</title>
</head>
<body>
<h2>Graph Goes Here</h2>
{{ graph }}
</body>
</html>
I have an answer to my own question, I was simply able to add the image url into the template, without trying to pass it in as a variable.
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>{{ title }}</title>
</head>
<body>
<h2>Graph Goes Here</h2>
<img src="graph.png">
</body>
</html>
Guess I was over complicating it a bit...

Issue with HTTP GET Parameters in Python CGI

I am learning web development in Python. When I open the HTML I get the Ferrari Fiat Ford, which is what I am expecting but then I click on Ferrari and it opens up the new page as make, model, which is not what I want. I want Ferrari Dino.
Could you help me understand what is the problem?
<!DOCTYPE HTML>
<html lang ="en">
<head>
<meta charset="UTF-8">
<title>Python Response</title>
</head>
<body>
<h1>
Ferrari
<a href = 'get.py?make = Fiat & model = Topolino'>Fiat</a>
<a href = 'get.py?make = Ford & model = Mustang'>Ford</a>
</h1>
</body>
</html>
Python
import cgi
data = cgi.FieldStorage()
make = data.getvalue('make')
model = data.getvalue('model')
print ( 'Content-type:text/html\r\n\r\n' )
print ( '''<!DOCTYPE HTML><html lang = "en">
<head>
<meta charset="UTF-8">
<title>Python Response</title>
</head>
<body>
<h1>, make, model,</h1>
Back
</body>
</html>''' )
A variable cannot be a string.
import cgi
data = cgi.FieldStorage()
make = data.getvalue('make')
model = data.getvalue('model')
print ( 'Content-type:text/html\r\n\r\n' )
print ( '''<!DOCTYPE HTML><html lang = "en">
<head>
<meta charset="UTF-8">
<title>Python Response</title>
</head>
<body>
<h1>, ''' + make + ', ' + model + ''',</h1>
Back
</body>
</html>''' )
After testing this out, the HTML is responding as anticipated.
My recommendation goes along lines of this question here: How to pass python variable to html variable?
In summary, you could do this in a better way by writing a function and returning the html. Also, once you've written the python function, rather than have the:
<h1>, make, model,</h1>
You could use a substitution in your python function like so:
"<h1>, %s, %s,</h1>" % (make, model)
Which would be located in the same python file as the two of these variables.
Your template outputs this:
<h1>, make, model,</h1>
And that's all it ever will output. You can instead change it a little and then use the format method to insert values into it.
html = '''<!DOCTYPE HTML><html lang = "en">
<head>
<meta charset="UTF-8">
<title>Python Response</title>
</head>
<body>
<h1>, {make}, {model},</h1>
Back
</body>
</html>'''
print html.format(make=make, model=model)
The values in curlybraces, {make} and {model}, are named tokens inside the string. When you use format() on the string called html, you replace those tokens. In this case, I referenced them directly by name.

Append before closing body tag in python

ok guys so I have a template.html file like so:
<h1>Hello wolrd</h1>
<div>This is me</div>
And I want to append that to my index file before the closing body tag. Just like so:
<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title></title>
</head>
<body>
<script type="text/ng-template" id="templates/template.html">
<h1>Hello wolrd</h1>
<div>This is me</div>
</script>
</body>
</html>
I've so far gotten to read the file and append to the end of it but I have yet to add the script tags to the file that I am reading and append to the correct spot of my file. This is what I currently have:
#!/usr/bin/env python
import fileinput
to_readfile=open('index.html', "r")
try:
reading_file=to_readfile.read()
writefile=open('index2.html','a')
try:
writefile.write("\n")
writefile.write(reading_file)
finally:
writefile.close()
finally:
to_readfile.close()
Any help would be much appreciated. Thank you!
The simplest approach would be to add a placeholder in the layout template and then when processing the layout search for the placeholder and replace it with the contents of the other template.
<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title></title>
</head>
<body>
<script type="text/ng-template" id="templates/template.html">
{{content}}
</script>
</body>
</html>
...
..
.
layout = open('layout.html', "r")
layout_contents = layout.read()
partial=open('partial_file.html','r')
result = layout_contents.replace("{{content}}", partial)
writefile = open("file_to_write.html", "w")
writefile.write("\n")
writefile.write(result)
.
..
....
You can also work on a much more extensive solution such as the ones used by jinja http://jinja.pocoo.org/docs/templates/#template-inheritance.

Categories

Resources