Why request.form from input fields not work? - python

I have an HTML page with a form compiled yet with default values as a modify form, in python program i want to get the modified information, if there are. i have a ID to use for update the data in my DB with pymssql. When i get data from the form in HTML page, the ID it's get, but the CF block the program and give me the error: POST/[name_page] HTTP/1.1" 400
PYTHON
#app.route('/salva_modifiche_paziente',methods=['POST'])
def dati_paziente_modificato():
id = dett_id_paz()
cf = request.form.get['cf']
nome = request.form['nome']
cognome = request.form['cognome']
data_nascita = request.form['data_nascita']
residenza = request.form['residenza']
grado_dolore = request.form['grado_dolore']
sintomi = request.form['sintomi']
data_ricovero = request.form['data_ricovero']
data_dimissione = request.form['data_dimissione']
reparto = request.form['reparto']
n_stanza = request.form['n_stanza']
n_letto = request.form['n_letto']
modifica_paziente(id, cf, nome, cognome, data_nascita, residenza, grado_dolore, sintomi, data_ricovero,
data_dimissione, reparto, n_stanza, n_letto)
dett = dettagli_paziente_ricoverato()
return render_template('dettagli_paziente_ricoverato.html', det_paz=dett)
def modifica_paziente(id,cf,nome,cognome,data_nascita,residenza,grado_dolore,sintomi,data_ricovero,data_dimissione,reparto,n_stanza,n_letto):
connection1 = pymssql.connect(database="UNICLINIC")
connection2 = pymssql.connect(database="UNICLINIC")
cursor1 = connection1.cursor()
cursor2 = connection2.cursor()
cursor1.execute("UPDATE paziente SET CF = (%s), nome = (%s), cognome = (&s), \
data_di_nascita = (%s), residenza = (%s), grado_dolore = (%d), sintomi = (%s) WHERE ID_paziente = %d",(cf,nome,cognome,data_nascita,residenza,grado_dolore,sintomi, int(id) ))
cursor2.execute("UPDATE ricoverato SET data_ricovero = (6s), \
data_dimissione = (%s), COD_reparto = (%s), n_stanza = (%s), n_letto = (%s) \
WHERE ID_paziente = (%d)"
,(data_ricovero, data_dimissione, reparto, n_stanza, n_letto,int(id)))
connection1.commit()
connection2.commit()
cursor1.close()
cursor2.close()
connection1.close()
connection2.close()
def dett_id_paz():
id = request.form['id_paziente']
print(id)
return id
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Modifica paziente | UNICLINIC</title>
<link rel="stylesheet" href={{ url_for('static', filename='style.css') }} type="text/css" media="all"/>
</head>
<body>
<div>
<table class="head_banner">
<tr>
<td><img id="logo" src={{ url_for('static', filename='immagini/logo_uniclinic.png') }} alt="Logo UNICLINIC"/></td>
<td class="menu"><button class="menu_btn">HOME</button></td>
<td class="menu"><button class="menu_btn">LOGIN</button></td>
<td class="menu"><button class="menu_btn">CONTACTS</button></td>
</tr>
</table>
<table class="tab_hd">
<thead>
<th>
<td colspan="2" id="p_tit">Dati profilo di {{det_paz.nome}} {{det_paz.cognome}}<td>
</th>
</thead>
</table>
<table class="tab_profilo">
<form id="modifica" method="post" action="salva_modifiche_paziente" class="form">
<tr>
<td class="p_dn">ID paziente:</td>
<td class="p_dv">
{{det_paz.id}}
<input style="display:none" id="id_paziente" name="id_paziente" type="text" value="{{det_paz.id}}" />
</td>
</tr>
<tr>
<td class="p_dn">Codice Fiscale:</td>
<td class="p_dv">
<input type="text" id="cf" name="cf " value="{{det_paz.cf}}"/>
</td>
</tr>
<tr>
<td class="p_dn">Nome:</td>
<td class="p_dv">
<input type="text" id="nome" name="nome" value="{{det_paz.nome}}"/>
</td>
</tr>
<tr>
<td class="p_dn">Cognome:</td>
<td class="p_dv">
<input type="text" id="cognome" name="cognome" value="{{det_paz.cognome}}"/>
</td>
</tr>
<tr>
<td class="p_dn">Data di nascita:</td>
<td class="p_dv">
<input type="date" id="data_nascita" name="data_nascita" value="{{det_paz.data_nascita}}"/>
</td>
</tr>
<tr>
<td class="p_dn">Residenza:</td>
<td class="p_dv">
<input type="text" id="residenza" name="residenza" value="{{det_paz.residenza}}"/>
</td>
</tr>
<tr>
<td class="p_dn">Grado dolore:</td>
<td class="p_dv">
<select name="grado_dolore" id="grd_d">
{% for g in range(10) %}
<option type="text" id="grado_dolore" name="grado_dolore" value="{{g+1}}">Grado {{g+1}}</option>
{% endfor %}
</select>
</td>
</tr>
<tr>
<td class="p_dn">Sintomi:</td>
<td class="p_dv">
<input type="text" id="sintmi" name="sintomi" value="{{det_paz.sintomi}}"/>
</td>
</tr>
<tr>
<td class="p_dn">Data ricovero:</td>
<td class="p_dv">
<input type="date" id="data_ricovero" name="data_ricovero" value="{{det_paz.data_ricovero}}"/>
</td>
</tr>
<tr>
<td class="p_dn">Data dimissione:</td>
<td class="p_dv">
<input type="date" id="data_dimissione" name="data_dimissione" value="{{det_paz.data_dimissione}}"/>
</td>
</tr>
<tr>
<td class="p_dn">Reparto ricovero:</td>
<td class="p_dv">
<label for="reparto"></label>
<select name="reparto" id="rep" class="p_dv">
{% for reparto in rep %}
<option type="text" id="reparto" name="reparto" value="{{reparto.COD_reparto}}">{{reparto.COD_reparto}} - {{reparto.nome_reparto}}</option>
{% endfor %}
</select>
</td>
</tr>
<tr>
<td class="p_dn">Stanza nr.:</td>
<td class="p_dv">
<input type="text" id="n_stanza" name="n_stanza" value="{{det_paz.n_stanza}}"/>
</td>
</tr>
<tr>
<td class="p_dn">Letto nr.:</td>
<td class="p_dv">
<input type="text" id="n_letto" name="n_letto" value="{{det_paz.n_letto}}"/>
</td>
</tr>
<tr class="r_bd">
<td class="b_dn"><button type="submit" form="modifica" class="menu_btn_d">CONFERMA</button></td>
<td class="b_dn"><button type="reset" class="menu_btn_d">ANNULLA</button></td>
</tr>
</form>
</table>
</div>
</body>
</html>

Related

Adding Data To Email Through Loop In Python

I am attempting to iterate through a map containing arrays to an HTML email template. I can print out the data in the array but, the data does not show up in the array after finishing the loop.
html_data = """
<!DOCTYPE html>
<html lang="en">
<head></head>
<body>
<br>
<br>
Date: {{date}}
<br>
<br>
Hi,
<br>
<br>
Today's Picks Are in:
<br>
<br>
<div class="card-body">
<table class="table table-sm">
<thead>
<tr>
<th align='left'>Stock</th>
<th>Pick</th>
<th>Detail</th>
<th>Change</th>
</tr>
</thead>
<tbody>
<td align='left'>{{ picks }}</td>
{% for pick in picks %}
<tr>
<td align='center'> {{pick.stock}} </td>
# <td align='center'> {{pick.prices}} </td>
# <td align='center'>{{pick.option_details}}</td>
# <td align='center'>{{pick.change}}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<br>
<br>
<p>If you would like to be removed from this list, please contact customer service: <mail_to="devs#hscottindustriescom">HScottIndustries</a> </p>
"""
Picks is the mapped array
picks = {
'stocks': stocks,
'prices': stock_price,
'option_details': options_details,
'change': change
}
The data from picks is added here.
msg = MIMEText(Environment().from_string(html_data).render(picks=picks, date=date_original), "html")
The output is this:
<!DOCTYPE html>
<html lang="en">
<head></head>
<body>
<br>
<br>
Date: 07-05-2022
<br>
<br>
Hi,
<br>
<br>
Today's Picks Are in:
<br>
<br>
<div class="card-body">
<table class="table table-sm">
<thead>
<tr>
<th align='left'>Stock</th>
<th>Pick</th>
<th>Detail</th>
<th>Change</th>
</tr>
</thead>
<tbody>
<td align='left'>{'stocks': ['WPP', 'NEX', 'PTEN'], 'prices': ['45.21', '8.37', '13.39'], 'option_details': ['na', 'NEX Jul 15 2022 $7.50 Put', 'PTEN Jul 15 2022 $13.00 Put'], 'change': ['-10.19%', '-11.52%', '-11.53%']}</td>
<tr>
<td align='center'> </td>
# <td align='center'> </td>
# <td align='center'></td>
# <td align='center'></td>
</tr>
<tr>
<td align='center'> </td>
# <td align='center'> </td>
# <td align='center'></td>
# <td align='center'></td>
</tr>
<tr>
<td align='center'> </td>
# <td align='center'> </td>
# <td align='center'></td>
# <td align='center'></td>
</tr>
<tr>
<td align='center'> </td>
# <td align='center'> </td>
# <td align='center'></td>
# <td align='center'></td>
</tr>
</tbody>
</table>
</div>
<br>
<br>
<p>If you would like to be removed from this list, please contact customer service: HScottIndustries </p>
<footer class="main-footer">
<strong>Copyright © 2022 <mail_to="devs#HScottIndustries.com">HScottIndustries LLC</a></strong>
How do I add the get the data to iterate correctly to the corresponding fields?
You are iterating over picks, which right now is a dictionary, meaning you will get dictionary keys in return. You can either format picks in a different way, or use an index. This format should work:
picks = [
{
'stocks': 'WPP',
'prices': '45.21',
'option_details': 'na',
'change': '-10.19%'
},
{
'stocks': 'NEX',
'prices': ...
},
...
]
Alternatively you can pass picks as zipped arrays in your view:
zipped_picks = zip(*picks.values())
Then access them with:
{% for pick in zipped_picks %}
<div> {{pick.0}} <div>
<div> {{pick.1}} <div>
<div> {{pick.2}} <div>
<div> {{pick.3}} <div>
{% endfor %}

HTML table to database

At this point, my table looks as follows:
<table border="0" cellpadding="0" cellspacing="0" class="ms-formtable" id="formTbl" style="margin-top: 8px;" width="100%">
<tbody>
<tr>
<td class="ms-formlabel" nowrap="true" valign="top" width="165px">
<h3 class="ms-standardheader">
<a name="SPBookmark_FileLeafRef">
</a>
Name
</h3>
</td>
<td class="ms-formbody" id="SPFieldFile" valign="top" width="450px">
<a href="http://google.com" onclick="DispDocItemEx(this, 'FALSE', 'FALSE', 'FALSE', '');">
X
</a>
</td>
</tr>
<tr>
<td class="ms-formlabel" nowrap="true" valign="top" width="165px">
<h3 class="ms-standardheader">
<a name="SPBookmark_Owner">
</a>
Name#
</h3>
</td>
<td class="ms-formbody" id="SPFieldChoice" valign="top" width="450px">
Z
</td>
</tr>
<tr>
<td class="ms-formlabel" nowrap="true" valign="top" width="165px">
<h3 class="ms-standardheader">
<a name="SPBookmark_DirectiveRank">
</a>
Age
</h3>
</td>
<td class="ms-formbody" id="SPFieldChoice" valign="top" width="450px">
52
</td>
</tr>
<tr>
<td class="ms-formlabel" nowrap="true" valign="top" width="165px">
<h3 class="ms-standardheader">
<a name="SPBookmark_Number">
</a>
number
</h3>
</td>
<td class="ms-formbody" id="SPFieldText" valign="top" width="450px">
1
</td>
</tr>
<tr>
<td class="ms-formlabel" nowrap="true" valign="top" width="165px">
<h3 class="ms-standardheader">
<a name="SPBookmark_Title">
</a>
Name of File
</h3>
</td>
<td class="ms-formbody" id="SPFieldText" valign="top" width="450px">
Funny Names
</td>
</tr>
<tr>
<td class="ms-formlabel" nowrap="true" valign="top" width="165px">
<h3 class="ms-standardheader">
<a name="SPBookmark_EffectiveFrom">
</a>
date
</h3>
</td>
<td class="ms-formbody" id="SPFieldDateTime" valign="top" width="450px">
1.1.2022
</td>
</tr>
</tbody>
</table>
I basically need to open an HTML file, filter table with id "formTbl" and then either create JSON with values : {Firsttd:Secondtd, "Name":"Test", "Date":"Blank"} or insert into database where First td (in tr tag we have 2 td, first it name of column and second is value) in table A and second td in table B. Is there any way? I´ve tried using Python, where I got so far json looks like [["","Name","","Test",""],["","Age","","12",""]] and in C# I´ve tried HTMLAgilityPack but it wasn´t working.
Here is the solution with JQuery.
<html>
<body>
<table id="example-table">
<tr>
<th>Name</th>
<th>Name#</th>
<th>Age</th>
<th>Number</th>
<th>Name of file</th>
<th>Date</th>
</tr>
<tr>
<td>X</td>
<td>Z</td>
<td>52</td>
<td>1</td>
<td>Name of file</td>
<td>2021-22-10</td>
</tr>
</table>
<textarea rows="10" cols="50" id="jsonTextArea">
</textarea>
</body>
</html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/table-to-json#1.0.0/lib/jquery.tabletojson.min.js"></script>
<script type="text/javascript">
var tableToJson = $('#example-table').tableToJSON();
var sendingData = JSON.stringify (tableToJson);
$('#jsonTextArea').val(sendingData);
// Send JSON data to backend
$.post('http://localhost/test.php', {sendingData}, function(data, textStatus, xhr) {
var backendResponse = data;
console.log(backendResponse);
});
</script>

Django: Unable to use prefetch_related

What I want to do is that for a particular Cylinder Id , if cylinder is issued then the user name and the issue date will be displayed in cylinder List , like this
cylinderId | date | type | status |availability| issuedate | userName | returndate |
1 | 11/11| co2 | fill | available| 12/11(if exists)| xyz | 13/11(if exists)
so for that i used prefetch_related but it is not displaying anything in cylinder List:-
here is model:-
class Cylinder(models.Model):
stachoice=[
('Fill','fill'),
('Empty','empty')
]
substachoice=[
('Available','available'),
('Unavailable','unavailable'),
('Issued','issued')
]
cylinderId=models.CharField(max_length=50,primary_key=True,null=False)
gasName=models.CharField(max_length=200)
cylinderSize=models.CharField(max_length=30)
Status=models.CharField(max_length=40,choices=stachoice,default='fill')
Availability=models.CharField(max_length=40,choices=substachoice,default="Available")
EntryDate=models.DateTimeField(default=timezone.now)
def get_absolute_url(self):
return reverse('cylinderDetail',args=[(self.cylinderId)])
def __str__(self):
return str(self.cylinderId)
class Issue(models.Model):
cylinder=models.ForeignKey('Cylinder',on_delete=models.CASCADE)
userName=models.CharField(max_length=60,null=False)
issueDate=models.DateTimeField(default=timezone.now)
def save(self,*args,**kwargs):
if not self.pk:
if self.cylinder.Availability=='Available':
Cylinder.objects.filter(cylinderId=self.cylinder.cylinderId).update(Availability=('Issued'))
super().save(*args,**kwargs)
def __str__(self):
return str(self.userName)
here is cylinder list view:-
def cylinderListView(request):
cylinder=Cylinder.objects.all().prefetch_related('issue_set')
return render(request,'entry/cylinderList.html',locals())
here is cylinderList template:-
{% extends 'base.html'%}
{% block content %}
<div class="alldiv">
<h1 align="center">All Cylinder list</h1>
{% if cylinder %}
<div class='centerstage'>
<div class="post">
<table border="5" cellspacing="5" width="100%" >
<thead>
<tr bgcolor="#99c2ff"align="center">
<th height="50"
width="50">Cylinder Id</th>
<th height="50"
width="50">Date</th>
<th height="50"
width="50">Gas Name</th>
<th height="50"
width="50">Cylinder Size</th>
<th height="50"
width="50">Status</th>
<th height="50"
width="50">Availability</th>
<th height="50"
width="50">Issued Date</th>
<th height="50"
width="50">Customer</th>
<th height="50"
width="50">Return Date</th>
</thead>
<tbody>
{%for cy in cylinder%}
<tr bgcolor="#e6f0ff" align="center">
<td align="center" height="10"
width="50"><a href="{{cy.get_absolute_url}}">{{cy.cylinderId}}<a></td>
<td align="center" height="10"
width="50">{{cy.EntryDate}}</td>
<td align="center" height="10"
width="50">{{cy.gasName}}</td>
<td align="center" height="10"
width="50">
{{cy.cylinderSize}}</td>
<td align="center" height="10"
width="50">
{{cy.Status}}</td>
<td align="center" height="10"
width="50">{{cy.Availability}}</td>
<td align="center" height="10"
width="50">{{cy.issue.issueDate}}</td>
<td align="center" height="10"
width="50">{{cy.issue.userName}}</td>
</tr>
{% endfor %}
</tbody>
{% else %}
<div>
<h2>No record</h2>
</div>
</table>
</div>
</div>
</div>
{% endif %}
{% endblock %
}
I m unable to figure out that what i m missing , Is I m using prefetch_related?
You need to cycle through the issue_set like so:
{% for issue in cy.issue_set.all() %}
<td align="center" height="10" width="50">{{ issue.issueDate }}</td>
<td align="center" height="10" width="50">{{ issue.userName }}</td>
{% endfor %}

Can't parse a second table with beautifulsoup even if the first one works?

I am trying to parse tables using beautifulsoup. The first one on my page was easy but I cannot parse a similar table on the same page. I do not understand why.
Here is the code. Thanks in advance for your help.
import urllib2
from bs4 import BeautifulSoup
url = urllib2.urlopen("https://dl.dropboxusercontent.com/u/956261/poftext.html")
contentHTML = url.read()
soup = BeautifulSoup(contentHTML)
tableUserDetails = soup.find("table", {"class" : "user-details"})
i = 0
tableUserDetailsList = []
for row in tableUserDetails.findAll('tr'):
for col in row.findAll('td'):
contentTd = col.contents[0].string.strip()
if contentTd:
print "TD Number %d : %s" % (i, contentTd)
tableUserDetailsList.append(contentTd)
i += 1
# This first table is OK
print tableUserDetailsList
# But now this one
tableUserDetails = soup.find("table", {"class" : "secondpart"})
i = 0
tableUserDetailsList = []
for row in tableUserDetails.findAll('tr'):
for col in row.findAll('td'):
contentTd = col.contents[0].string.strip()
if contentTd:
print "TD Number %d : %s" % (i, contentTd)
tableUserDetailsList.append(contentTd)
i += 1
print tableUserDetailsList
# The list is empty :(
Here is a simplified version of the HTML code that I am trying to parse:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>
French.Kiss
Sorties, Sport, Voyages, Nouvelles Expériences</title>
</head>
<body style='background-color: #fff;' leftMargin='0' topMargin='0' marginwidth='0' marginheight='0' link='#1E55D6' vlink='#1E55D6' TEXT='#6551b0'>
<table class="user-details">
<tr>
<td class="headline txtBlue size15" style="width:80px">
About
</td>
<td style="width:10px">
</td>
<td class="txtGrey size15">
Fume occasionnellement with Silhouette mince
</td>
<td width="25px;">
</td>
<td class="headline txtBlue size15">
City
</td>
<td class="txtGrey size15">
Paris Ile-de-France
</td>
</tr>
<tr>
<td class="headline txtBlue size15">
Details
</td>
<td style="width:10px">
</td>
<td class="txtGrey size15">
26 year old Un homme, 185cm, Sans religion
</td>
<td>
</td>
<td class="headline txtBlue size15">
Ethnicity
</td>
<td class="txtGrey size15">
Caucasienne Balance with Châtains
</td>
</tr>
<tr>
<td class="headline txtBlue size15">
Intent
</td>
<td style="width:10px">
</td>
<td class="txtGrey size15">
French.Kiss Cherche une relation amoureuse.
</td>
<td>
</td>
<td class="headline txtBlue size15" style="width:90px">
Education
</td>
<td class="txtGrey size15">
Diplôme universitaire/Licence
</td>
</tr>
<tr>
<td class="headline txtBlue size15">
Personnalité
</td>
<td style="width:10px">
</td>
<td class="txtGrey size15">
</td> <td>
</td>
<td>
<span class="headline txtBlue size15">Profession </span>
</td>
<td>
<span class="txtGrey size15">
Visioconférence</span>
</td>
</tr>
</table>
<table width="85%" class="secondpart">
<tr height="25px">
<td width="200px">
<span class="headline txtBlue size14">I am Seeking a</span>
</td>
<td width="300px">
<span class="txtGrey size14">
Une femme</span>
</td>
<td width="25px">
</td>
<td width="200px">
<span class="headline txtBlue size14">For</span>
</td>
<td width="200px">
<span class="txtGrey size14">
Sorties</span>
</td>
</tr>
<tr height="25px">
<td>
<span class="headline txtBlue size14"><a href='needs_test.aspx'>Needs Test</a></span>
</td>
<td>
<span class="txtGrey size14"><a href='needs_test.aspx'>
<a href="needs_view.aspx?id=38028200">View
his
relationship needs</a></a></span>
</td>
<td>
</td>
<td>
<span class="headline txtBlue size14"><a href='poftest.aspx'>Chemistry</a></span>
</td>
<td>
<span class="txtGrey size14"><a href='poftest.aspx'>
<a href="personality.aspx?id=26&user_id=41724176" rel="nofollow">View
his
chemistry results</a></a></span>
</td>
</tr>
<tr height="25px">
<td>
<span class="headline txtBlue size14">Do you drink?</span>
</td>
<td>
<span class="txtGrey size14">
Occasionnellement</span>
</td>
<td>
</td>
<td>
<span class="headline txtBlue size14">Do you want children?</span>
</td>
<td>
<span class="txtGrey size14">
Non divulgué</span>
</td>
</tr>
<tr height="25px">
<td>
<span class="headline txtBlue size14">Marital Status</span>
</td>
<td>
<span class="txtGrey size14">
Célibataire</span>
</td>
<td>
</td>
<td>
<span class="headline txtBlue size14">Do you do drugs?</span>
</td>
<td>
<span class="txtGrey size14">
Non</span>
</td>
</tr>
<tr height="25px">
<td>
<span class="headline txtBlue size14">Pets </span>
</td>
<td>
<span class="txtGrey size14">
Aucun</span>
</td>
<td>
</td>
<td>
<span class="headline txtBlue size14">Eye Color</span>
</td>
<td>
<span class="txtGrey size14">
Bruns</span>
</td>
</tr>
<tr height="25px">
<td>
<span class="headline txtBlue size14">Do you have a car? </span>
</td>
<td>
<span class="txtGrey size14">
N/A</span>
</td>
<td>
</td>
<td>
<span class="headline txtBlue size14">Do you have children?</span>
</td>
<td>
<span class="txtGrey size14">
Non</span>
</td>
</tr>
<tr height="25px">
<td>
<span class="headline txtBlue size14">Longest Relationship</span>
</td>
<td>
<span class="txtGrey size14">
Plus de 2 ans</span>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
</tr>
</table>
</body>
</html>
tableUserDetails.content, tableUserDetails and tableUserDetailsList for both tables:
* FIRST TABLE *
print tableUserDetails.content = none
print tableUserDetails =
<table class="user-details">
<tr>
<td class="headline txtBlue size15" style="width:80px">
About
</td>
<td style="width:10px">
</td>
<td class="txtGrey size15">
Fume occasionnellement with Silhouette mince
</td>
<td width="25px;">
</td>
<td class="headline txtBlue size15">
City
</td>
<td class="txtGrey size15">
Paris Ile-de-France
</td>
</tr>
<tr>
<td class="headline txtBlue size15">
Details
</td>
<td style="width:10px">
</td>
<td class="txtGrey size15">
26 year old Un homme, 185cm, Sans religion
</td>
<td>
</td>
<td class="headline txtBlue size15">
Ethnicity
</td>
<td class="txtGrey size15">
Caucasienne Balance with Châtains
</td>
</tr>
<tr>
<td class="headline txtBlue size15">
Intent
</td>
<td style="width:10px">
</td>
<td class="txtGrey size15">
French.Kiss Cherche une relation amoureuse.
</td>
<td>
</td>
<td class="headline txtBlue size15" style="width:90px">
Education
</td>
<td class="txtGrey size15">
Diplôme universitaire/Licence
</td>
</tr>
<tr>
<td class="headline txtBlue size15">
Personnalité
</td>
<td style="width:10px">
</td>
<td class="txtGrey size15">
</td> <td>
</td>
<td>
<span class="headline txtBlue size15">Profession </span>
</td>
<td>
<span class="txtGrey size15">
Visioconférence</span>
</td>
</tr>
</table>
print tableUserDetailsList = [u'About', u'Fume occasionnellement with Silhouette mince', u'City', u'Paris Ile-de-France', u'Details', u'26 year old Un homme, 185cm, Sans religion', u'Ethnic
ity', u'Caucasienne Balance with Ch\xe2tains', u'Intent', u'French.Kiss Cherche
une relation amoureuse.', u'Education', u'Dipl\xf4me universitaire/Licence', u'P
ersonnalit\xe9']
* SECOND TABLE *
print tableUserDetails.content = none
print tableUserDetails =
<table width="85%" class="secondpart">
<tr height="25px">
<td width="200px">
<span class="headline txtBlue size14">I am Seeking a</span>
</td>
<td width="300px">
<span class="txtGrey size14">
Une femme</span>
</td>
<td width="25px">
</td>
<td width="200px">
<span class="headline txtBlue size14">For</span>
</td>
<td width="200px">
<span class="txtGrey size14">
Sorties</span>
</td>
</tr>
<tr height="25px">
<td>
<span class="headline txtBlue size14"><a href='needs_test.aspx'>Needs Test</a></span>
</td>
<td>
<span class="txtGrey size14"><a href='needs_test.aspx'>
<a href="needs_view.aspx?id=38028200">View
his
relationship needs</a></a></span>
</td>
<td>
</td>
<td>
<span class="headline txtBlue size14"><a href='poftest.aspx'>Chemistry</a></span>
</td>
<td>
<span class="txtGrey size14"><a href='poftest.aspx'>
<a href="personality.aspx?id=26&user_id=41724176" rel="nofollow">View
his
chemistry results</a></a></span>
</td>
</tr>
<tr height="25px">
<td>
<span class="headline txtBlue size14">Do you drink?</span>
</td>
<td>
<span class="txtGrey size14">
Occasionnellement</span>
</td>
<td>
</td>
<td>
<span class="headline txtBlue size14">Do you want children?</span>
</td>
<td>
<span class="txtGrey size14">
Non divulgué</span>
</td>
</tr>
<tr height="25px">
<td>
<span class="headline txtBlue size14">Marital Status</span>
</td>
<td>
<span class="txtGrey size14">
Célibataire</span>
</td>
<td>
</td>
<td>
<span class="headline txtBlue size14">Do you do drugs?</span>
</td>
<td>
<span class="txtGrey size14">
Non</span>
</td>
</tr>
<tr height="25px">
<td>
<span class="headline txtBlue size14">Pets </span>
</td>
<td>
<span class="txtGrey size14">
Aucun</span>
</td>
<td>
</td>
<td>
<span class="headline txtBlue size14">Eye Color</span>
</td>
<td>
<span class="txtGrey size14">
Bruns</span>
</td>
</tr>
<tr height="25px">
<td>
<span class="headline txtBlue size14">Do you have a car? </span>
</td>
<td>
<span class="txtGrey size14">
N/A</span>
</td>
<td>
</td>
<td>
<span class="headline txtBlue size14">Do you have children?</span>
</td>
<td>
<span class="txtGrey size14">
Non</span>
</td>
</tr>
<tr height="25px">
<td>
<span class="headline txtBlue size14">Longest Relationship</span>
</td>
<td>
<span class="txtGrey size14">
Plus de 2 ans</span>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
</tr>
</table>
print tableUserDetailsList = []
This works:
tableUserDetailsList = []
for row in tableUserDetails.findAll('tr'):
for col in row.findAll('td'):
contents = list(col.stripped_strings)
if contents:
contentTd = contents[0]
print "TD Number %d : %s" % (i, contentTd)
tableUserDetailsList.append(contentTd)
i += 1
The problem was that your second table contains spans. The line break before the span was also interpreted as content and returned in the col.contents list.
It also works for the first table. As Anubhav commented, you should really consider iterating over the tables and not having the same code twice.
Instead using table = soup.find('table')
Use table = soup.find_all('table')
This will return a list of tables in your html, and you can then pick the correct one from the list.

How to select radio buttons and submit a form

This is the HTML:
<form method="post" action="./xxxxx" name="form1">
<input type="hidden" name="requestKey" value="52032a76cf53340b07052fd143feddc4a9d8f18130c80ec86003ab56e0d91b36"/>
<input type="hidden" name="option" value="txnlist">
<input type="hidden" name="account" value='1336169999'>
<input type="hidden" name="app" value="D">
<input type="hidden" name="lockType" value="">
<p><span class="header2"> Statement options </span>
<table summary="" width="100%" border="0" cellpadding="1" cellspacing="1">
<tr>
<td width="20"></td>
<td width="20"><input type="radio" name="optDateFilter" value="1"></td>
<td>Transactions for the last 30 days</td>
<td></td>
</tr>
<tr>
<td width="20"></td>
<td width="20"><input type="radio" name="optDateFilter" value="2"></td>
<td>Transactions for the last 90 days</td>
<td></td>
</tr>
<tr>
<td width="20"> </td>
<td width="20"><input type="radio" name="optDateFilter" checked='checked' value="3" style="vertical-align: middle"></td>
<td>
<div>
<font style="vertical-align: middle;">Transactions from </font>
<script src='jquery/js/ui/min/jquery.ui.datepicker.min-1.8.10.js'></script>
<script type='text/javascript'>$(function() {$('#datepicker1').datepicker( { changeMonth : true, changeYear : true, dateFormat : 'dd/mm/yy', showOn: 'both', buttonImage: 'images/calendar.png', buttonImageOnly: true }); }); </script>
<input type='text' id='datepicker1' name='txtFromDate' size='11' maxlength='10' value='14/12/2012' onchange="checkFromDate(document.form1.txtFromDate.value);document.form1.optDateFilter[2].checked = true;">
<font style="vertical-align: middle;">to</font>
<script type='text/javascript'>$(function() {$('#datepicker2').datepicker( { changeMonth : true, changeYear : true, dateFormat : 'dd/mm/yy', showOn: 'both', buttonImage: 'images/calendar.png', buttonImageOnly: true }); }); </script>
<input type='text' id='datepicker2' name='txtToDate' size='11' maxlength='10' value='01/01/2013' onchange="checkToDate(document.form1.txtFromDate.value,document.form1.txtToDate.value);document.form1.optDateFilter[2].checked = true;">
</div>
</td>
<td><font style="font-size: 8pt; vertical-align: middle;"><i>(maximum date range 3 months)</i></font></td>
</tr>
</table>
<table summary="" cellpadding="1" cellspacing="1" border="0">
<tr>
<td width="20"> </td>
<td width="20">
<a href="javascript:if(document.form1.optDateFilter[2].checked==true){CheckAndSubmit(document.form1.txtFromDate.value,document.form1.txtToDate.value);}else{showOverlay();document.form1.submit();};">
<img src="images/proceed.gif" alt="Show the selected range of transactions" border="0" width="22" height="22" />
</a>
</td>
<td>
Show the selected range of transactions
</td>
</tr>
</table>
</form>
This is the code i have, and it is not working:
self.browser.select_form('form1')
self.browser.form.set_all_readonly(False)
self.browser['txtFromDate'] = '28/12/12'
self.browser['txtToDate'] = '01/01/13'
resp = self.browser.submit()
html = resp.read()
I figured that i had to do this
self.browser.select_form('form1')
self.browser['optDateFilter'] = ['2']
self.browser.form.find_control(name="txtFromDate", id="datepicker1").value = "13/10/12"
self.browser.form.find_control(name="txtToDate", id="datepicker2").value = "01/01/13"
resp = self.browser.submit()
mechanize has a strange quirk: since there can be multiple radio button elements in a HTML document with the same name it insists that you use a list as value, even though only a single radio button may be selected at any time. That means that you need to use this:
self.browser.form.find_control(name='optDateFilter').value = ['2']
The same holds for checkboxes where it makes more sense because a user is allowed to select multiple values.

Categories