Getting value from an input in html using python - python

So, I'm making a program in python that is executed when the user gives values in an input in HTML. Everything runs OK.
from bs4 import BeautifulSoup # parsing
r = open("C:/Python27/Pruebas/pruebahtml.html")
soup = BeautifulSoup(r,"html.parser")
R4sem = soup.find("input",attrs={'id':'R4sem'})["value"]
R5sem = soup.find("input",attrs={'id':'R5sem'})["value"]
r.close()
txt = open('C:/Python27/Pruebas/Pruebaconfigfechas.txt','w')
Encabezado = """Due-Date-Function "DD_General"
Type PiecewiseConstant
Multiplier 1
Calculation-Policy Time-Relative
DueDate-Policy FODuedateToBucketEndTime
Attribute "FechaTope" \n"""
fechar4 = "\nDATE -4 weeks Score "
fechar5 = "\nDATE -5 weeks Score "
txt.write(Encabezado+fechar4+R4sem+fechar5+R5sem)
txt.close()
But when checking the new text file, R4sem and R5sem are empty. So my question is, I can't read the values that the inputs have or there's another way to do this. The users are gonna be usin the HTML constantly so the values are gonna be changing, so I thought that using inputs would be the best solution.
If needed I can put also the HTML code I have.
EDIT: Here's the HTML code.
<!DOCTYPE html>
<html>
<head>
<title>*AJAW*</title>
</head>
<body>
<p>Penalidadeshtml v0.1.3</p>
<div>
<form action="file:///C:/Python27/Pruebas/dist/lectura.exe">
Retraso 4 sem: <input type="text" name="R4sem" id="R4sem" value=""><br>
Retraso 5 sem: <input type="text" name="R5sem" id="R5sem" value=""><br>
<br>
<input type="submit" value="Grabar">
</form>
</div>
</body>
</html>

Well, I solved this by creating the text file I needed in the HTML, so it was easier to send the values the user put and have the document I was asked to deliver.
Thanks for the comments.

Related

Having trouble executing a python script from the web browser

I'm new to HTML and looking to integrate a python script which runs after i retrieve values from a HTML page.
I'm trying to run a sample script which takes two values (name and number) and returns a list of unique codes.
This is my python script (forms.cgi).
#!C:\Python34\Python.exe
import CampaignID, cgi
print ("Content-Type: text/html\n\n")
form = cgi.FieldStorage()
name = form.getvalue('Name')
number = form.getvalue('Number')
codes = CampaignID.CodeGen(name,number)
print(codes)
This is my below HTML script
<html>
<head>
<title>Campaign generation</title>
</head>
<body>
<form name = 'Campaign' action = 'forms.cgi' method = 'get'>
<fieldset>
<legend> Enter your restaurant Name </legend>
<label>Name <input type = 'text' name ='Name' size = '30'></label>
<br/>
<legend> No. of Coupons </legend>
<label>Number <input type = 'text' name ='Number' size = '4'></label>
<br/>
<hr/>
<input type = 'submit' value = 'submit review'/>
</fieldset>
</form>
After filling in the values , i am getting the python file source code on the page. I'm running apache (XAMPP)
Please let me know where im going wrong.
KJ
Your action attribute is pointing to a local file on disk. It needs to be pointing to a URL served by Apache.

Parse HTML string from a file and remove element using xpath and write it to same file in python

For my project, I have to remove selective content from a html file using python xpath.
The selective element can be removed using .remove() method, however the content in file looks same.
How do I write the modified content to that file again?
Though If i try to write the same tree object to file using open().write(etree.tostring(tree_obj)), will the content differs for unicode pages? Is there anyother way to keep the modified file?
Why the header tags in below output has different value after printing the tree object?
Please suggest.
Below is my code sample.
Example: I need to remove all div tags inside the html page.
HTML file:
<html>
<head>test</head>
<body>
<p>welcome to the world</p>
<div id="one">
<p>one</p>
<div id="one1">one1</div>
<ul>
<li>ones</li>
<li>twos</li>
<li>threes</li>
</ul>
</div>
<div id="hell">
<p>heaven</p>
<div id="one1">one1</div>
<ul>
<li>ones</li>
<li>twos</li>
<li>threes</li>
</ul>
</div>
<input type="text" placeholder="enter something.." />
<input type="button" value="click" />
</body>
</html>
Python file:
# _*_ coding:utf-8 _*_
import os
import sys
import traceback
import datetime
from lxml import etree, html
import shutil
def process():
fd=open("D:\\hello.html")
tree = html.fromstring(fd.read())
remove_tag = '//div'
for element in tree.xpath(remove_tag):
element.getparent().remove(element)
print etree.tostring(tree)
process()
OUTPUT:
<html>
<head/><body><p>test
</p>
<p>welcome to the world</p>
<input type="text" placeholder="enter something.."/>
<input type="button" value="click"/>
</body></html>
I haven't worked on python but i have played with parsing html based websites using Java with help of library jsoup.
Python also has similar one like this. Beautiful soup. You can play with this thing to get desired output.
Hope it helps.
Have you tried using python's standard library re?
import re</br>
re.sub('<.*?>','', '<nb>foobar<aon><mn>')
re.sub('</.*?>','', '</nb>foobar<aon><mn>')
The above two operations could be used in combination to remove all the html tags. It can be easily modified to remove the div tags too.

Sending data to server flask html

I am trying to create a simple checkbox that sends the data to server here is my html code.
<form action="." method="POST">
<div class="checksheet">
<input id="XML Parser" class="checkbox" type="checkbox"/>XML Parser
<input id="Feed Parser" class="checkbox" type="checkbox"/>Feed Parser
<input id="Text Parser" class="checkbox" type="checkbox"/>Text Parser
<input id="Case Normalization" class="checkbox" type="checkbox"/>Case Normalization
<input id="Stemmer" class="checkbox" type="checkbox"/> Stemmer
</div>
<div class="submit"><input type="submit" value="Send" name="raw_text"></div>
</form>
What I am trying to do is very similar to the question asked here: Send Data from a textbox into Flask?
But except with the text box.. I have checkboxes.
But I get this error:
Not Found
The requested URL was not found on the server.
If you entered the URL manually please check your spelling and try again.
MY server side code (in flask) is:
#app.route('/raw_text.html')
def home ():
file = "sample.xml"
contents = open(file).read()
contents = contents.decode('utf-8')
return render_template('raw_text.html', contents=contents,file=file)
#app.route('/raw_text.html',methods=['POST'])
def get_data():
print "REQUEST ",request.form()
data = request.form['raw_text']
print data
return "Processed"
Any suggestions.
Thanks
A few things:
Your checkbox elements need a name attribute, this is what is used when the data is sent to the back end. Each checkbox that is related to each other needs to have the same name.
Your action attribute needs to point to a URL. If you are posting it to the same page as the form, you can remove the attribute.
ID's cannot contain spaces.
To be accessible the check boxes need <label>s,

Return python result to html

I have one test.html:
<form action="/cgi-bin/test.py" method="GET">
<input type="text" name="search">
<input type="submit" value="Submit">
</form>
<div id="res"></res>
And one python script test.py:
#....
print Result
#....
I want instead of printing result on the test.py, return it to the test.html and write it in the div with id res... How I can do that?
<form id="myform">
<input id="my_text">
<button id="submit_btn">
</form>
<div id="result">
</div>
<script>
//you need to use jquery for this part
$("#submit_btn").click( function() {
$("#result").load("/path/to/cgi?my_text="+$("#my_text").val())
})
</script>
something like that... (this is real hacky 1 minute post that is untested so it may need some work ...
your question really has nothing to do with python ... it is just web technology question ... it would be the same if it was a php or C# or whatever processing the form data
it has nothing to do with python because it doesnt matter how you are processing the form data ... this is just web technology it would work exactly the same with a perl script instead of a python script or with a C# instead of python or whatever ... you want to return some data back to a web page ... how you got the data is really not relevant
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
<body>
<form action="someother.html" method="get">
<input id="my_text">
<input type="button" id="my_button" value="click me">
</form>
<div id="result">
</div>
<script>
$("#my_button").click(function(){
$("#result").load("");
})
</script>
</body>
</html>
here is an example ... just paste it into a file.html and go to it and click the button ...
its just loading its self load("") so it should duplicate the data thats on the page when you click it ...
Well I understood your question in this way, maybe you are looking for other thing but i know a way that do exactly what are you looking for: Ajax.
Just make an ajax request to the cgi python and put the response into a div. Luckily, this is very easy nowadays.
If you know something about jQuery (a javascript framework) you should visit this link to getting started: http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery#Rate_me:_Using_Ajax
byeeee
print "Content-type:text/html\r\n\r\n"
print "<html>"
print "<head>"
print "<title>Hello - Second CGI Program</title>"
print "</head>"
print "<body>"
print "<h2>Hello World</h2>"
print "<p>Executing HTML code from python script</p>"
print "</body>"
print "</html>"

Displaying results from search API

I'm trying to get to grips with web2py/python. I want to get the user to fill in a search form, the term they search for is sent to my python script which should send the query to the blekko API and output the results to them in a new HTML page. I've implemented the following code but instead of my normal index page appearing, I'm getting the html response directly from blekko with '%(query)' /html appearing in it's search bar. Really need some help with this!
HTML form on the default/index.html page
<body>
<div id="MainArea">
<p align="center">MY SEARCH ENGINE</p>
<form name="form1" method="get" action="">
<label for="SearchBar"></label>
<div align="center">
<input name="SearchBar" type="text" id="SearchBar" value="" size = "100px"><br />
<input name="submit" type="submit" value="Search">
</div>
</form>
<p align="center"> </p>
Python code on the default.py controller
import urllib2
def index():
import urllib2
address = "http://www.blekko.com/?q='%(query)'+/html&auth=<mykey>"
query = request.vars.query
response = urllib2.urlopen(address)
html=response.read()
return html
I think you are misunderstanding how string formatting works. You need to put the address and query together still:
address = "http://www.blekko.com/?q='%(query)s'+/html&auth=<mykey>" % dict(query=request.vars.query)
Add a hidden field to your form, call it "submitted". Then reformat your controller function as such:
import urllib2
def index():
if request.vars.submitted:
address = "http://www.blekko.com/?q='%(query)'+/html&auth=<mykey>"
query = request.vars.query
response = urllib2.urlopen(address)
html=response.read()
return html
else:
return dict()
This will show your index page unless the form was submitted and the page received the "submitted" form variable.
The /html doesn't do anything. Glad your question got answered. There is python client code for the blekko search api here: https://github.com/sampsyo/python-blekko

Categories