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 %}
Related
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>
I am trying to create a PDF from an HTML page using pdf-kit, then send that pdf as an attachment in an email.
Here is my code to create the pdf, this seems to be working:
html = render_template("office_report.html",role=role, name=name,owner=off,reps=reps,all_weekly=all_weekly,we=we,totals=totals,cog=cog,all_weekly_rpt=True,off_rpt=off_rpt,v=v,adonors=adonors,ae=ae,ov=ov,pay_total=pay_total)
options = {"enable-local-file-access": None}
try:
pdf=pdfkit.from_string(html,False,options=options)
files = pdf
except Exception as e:
print(e)
pdf='ERROR'
Then I try to send the email, but do not understand how to attach the PDF to the Email.
try:
msg = Message('Owner Report ', sender = ("Brand Drivers",BD), recipients = ['jesswholt#gmail.com',BD,comp])
msg.body = "Weekly Report" + str(we)
with app.open_resource(files) as fp:
msg.attach("Owner Report", "invoice/pdf", fp.read())
mail.mail.send(msg)
print('sent')
except Exception as e:
print(e)
Here is the HTML that is converted into the PDF
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<title>Childhelp</title>
<meta content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0' name='viewport' />
<meta name="viewport" content="width=device-width" />
</head>
<body>
<div class="header">
<h4 class="title">Office Report <br>{{owner.owner_name}}<br>{{owner.office_ID}}</h4>
<p>WeekEnding: {{we.strftime('%m-%d-%Y')}}</p>
</div>
<table id="office_weekly" class="table table-hover table-striped">
<thead>
<th>Ambassador</th>
<th>Transactions</th>
<th>Total Payments</th>
<th>Items Sold</th>
<th>Hotlines</th>
<th>Bonuses</th>
<!-- <th>Total</th>-->
</thead>
<tbody>
{% for r in reps %}
<tr>
<td>
<strong>{{r.rep_name}}</strong><br>
{{r.rep_ID}}
</td>
{% for w in all_weekly if w.rep == r.rep_ID %}
<td>{{w.transactions}}</td>
<td>
Cash: ${{w.cash/100}}<br>
Check: ${{w.check/100}}<br>
Card: ${{w.card/100}}<br>
<strong>Total: ${{w.total/100}}</strong>
</td>
<td>
Sold: {{w.tot_itm}}<br>
Refunded: {{w.refunds}}<br>
Amount Refunded: {{"$%.2f" % (w.amount_refunded/100)}}<br>
Refund Dates {{w.dates_refunded}}
</td>
<td>
Active: {{w.subs}}<br>
Cancels: {{w.can}}
</td>
<td>{{"$%.2f" % (w.bonus | float)}}</td>
{% else %}
<td></td>
<td></td>
<td></td>
<td></td>
<td>Report Incomplete</td>
</tr>
{% endfor %}
{% endfor %}
<tr>
<td><hr></td>
<td><hr></td>
<td><hr></td>
<td><hr></td>
<td><hr></td>
<td><hr></td>
</tr>
</tbody>
<tbody>
<tr>
<th></th>
</tr>
<td>Office Sub Total:</td>
<td>{{totals.transactions}}
</td>
<td>
Cash: {{totals.cash}}<br>
Check: {{totals.check}}<br>
Card: {{totals.card}}<br>
Total: {{totals.sales}}<br>
Overrides: {{"$%.2f" % (ov | float)}}
</td>
<td>
Items: {{totals.t_items}}<br>
COG: {{"$%.2f" % (cog)}} per piece<br>
Total COG: {{"$%.2f" % (totals.total_cog)}}
</td>
<td>
Total Hotlines for Office:<br>
Active: {{totals.hotlines}}<br>
Canceled: {{totals.cancels}}<br>
Total Pay Hotlines: {{"$%.2f" % (totals.hotlines | float * 15)}}
</td>
<td>
Total Bonuses Paid: {{totals.bonus}}<br>
Items Refunded: {{totals.items_refunded}}<br>
Amount Refunded: {{totals.amount_refunded / 100}}
</td>
</tbody>
<tbody>
<tr>
<th> Line Items</th>
</tr>
<td></td>
<td></td>
<td><strong>Balance Carry: {{off_rpt.balance_carry}}</strong></td>
</tbody>
<tbody>
<td></td>
<td></td>
<td><strong>Deposit: {{off_rpt.deposit}}</strong></td>
</tbody>
<tbody>
<td></td>
<td></td>
<td><strong>Events: {{totals.events}}</strong></td>
</tbody>
<tbody>
<td></td>
<td></td>
<td><strong>Line Items:</strong></td>
<td>
Name: {{v.li1_n}}<br>
Amount: ${{v.li1_p}}<br>
Name: {{v.li2_n}}<br>
Amount: ${{v.li2_p}}<br>
Name: {{v.li3_n}}<br>
Amount: ${{v.li3_p}}<br>
Name: {{v.li4_n}}<br>
Amount: ${{v.li4_p}}
</td>
</tbody>
<tbody>
<td></td>
<td></td>
<td></td>
<td></td>
{% if pay_total %}
<td><strong>Owner Payout:</strong></td>
<td><strong>{{"$%.2f" % (pay_total | float)}}</strong></td>
{% else %}
<td><strong>Card Sales:</strong></td>
<td><strong>{{totals.card}}</strong></td>
{% endif %}
</tbody>
<tbody>
<td>
<h3>Hotline Signups</h3>
</td>
</tbody>
<thead>
<th>Donor Name</th>
<th>Ambassador</th>
<th>Signup Date</th>
<th>Canceled</th>
<!-- <th>Total</th>-->
</thead>
<tbody>
{% for d in adonors %}
<tr>
<td>{{d.donor_name}}</td>
{% for x in reps if x.rep_ID == d.rep_ID %}
<td>{{x.rep_name}}<br>{{x.rep_ID}}</td>
{% endfor %}
<td>{{d.monthly_start_date}}</td>
{% if d.donor_status == False %}
<td>{{d.monthly_stop_date}}</td>
{% else %}
<td style="color:green">Active</td>
{% endif %}
</tr>
{% endfor %}
</tbody>
</table>
<div class="col-md-18">
</div>
</body>
</html>
Instead of this:
with app.open_resource(files) as fp:
msg.attach("Owner Report", "invoice/pdf", fp.read())
just do this:
msg.attach("Owner Report", "invoice/pdf", pdf)
pdf (or files) contains your file as a bytes type object. So you don't need to use open_resource and read a file, because you already have the data you need.
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>
I want to get or select data from two different tables with same class.I tried getting it from 'soup.find_all' but formatting the data is getting tough.
There are two tables with same class. I need to get only values(not label) from the tables.
TABLE 1:
<div class="bh_collapsible-body" style="display: none;">
<table border="0" cellpadding="2" cellspacing="2" class="prop-list">
<tbody>
<tr>
<td class="item">
<table>
<tbody>
<tr>
<td class="label">Rim Material</td>
<td class="value">Alloy</td>
</tr>
</tbody>
</table>
</td>
<td class="item">
<table>
<tbody>
<tr>
<td class="label">Front Tyre Description</td>
<td class="value">215/55 R16</td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr>
<td class="item">
<table>
<tbody>
<tr>
<td class="label">Front Rim Description</td>
<td class="value">16x7.0</td>
</tr>
</tbody>
</table>
</td>
<td class="item">
<table>
<tbody>
<tr>
<td class="label">Rear Tyre Description</td>
<td class="value">215/55 R16</td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr>
<td class="item">
<table>
<tbody>
<tr>
<td class="label">Rear Rim Description</td>
<td class="value">16x7.0</td>
</tr>
</tbody>
</table>
</td>
<td></td>
</tr>
</tbody>
</table>
</div>
</div>
TABLE 2:
<div class="bh_collapsible-body" style="display: none;">
<table border="0" cellpadding="2" cellspacing="2" class="prop-list">
<tbody>
<tr>
<td class="item">
<table>
<tbody>
<tr>
<td class="label">Steering</td>
<td class="value">Rack and Pinion</td>
</tr>
</tbody>
</table>
</td>
<td></td>
</tr>
</tbody>
</table>
</div>
</div>
What i have tried:
I tried getting the first table contents from Xpath but its giving with both values and labels.
table1 = driver.find_element_by_xpath("//*[#id='features']/div/div[5]/div[2]/div[1]/div[1]/div/div[2]/table/tbody/tr[1]/td[1]/table/tbody/tr/td[2]")
I tried to split the data but not succeeded
I think you are looking for CSS selector tr:not(:has(tr)), this will select the inner-most <tr>:
from bs4 import BeautifulSoup
soup = BeautifulSoup(data, 'html.parser') # the variable data contains string for Table1 and Table2 in your question
rows = []
for tr in soup.select('tr:not(:has(tr))'):
rows.append([td.get_text(strip=True) for td in tr.select('td')])
for row in zip(*rows):
print(''.join('{: ^25}'.format(d) for d in row))
Prints:
Rim Material Front Tyre Description Front Rim Description Rear Tyre Description Rear Rim Description Steering
Alloy 215/55 R16 16x7.0 215/55 R16 16x7.0 Rack and Pinion
The variable rows contains:
[['Rim Material', 'Alloy'],
['Front Tyre Description', '215/55 R16'],
['Front Rim Description', '16x7.0'],
['Rear Tyre Description', '215/55 R16'],
['Rear Rim Description', '16x7.0'],
['Steering', 'Rack and Pinion']]
Further reading:
CSS Selectors Reference
EDIT: Changed to CSS Selector to tr:not(:has(tr))
Hey everyone I have some html that I am parsing, here it is:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<table class="dayinner">
<tr class="lun">
<td class="mealname" colspan="3">LUNCH</td>
</tr>
<tr class="lun">
<td class="station"> Deli</td>
<td class="menuitem">
<div class="menuitem">
<input class="chk" id="S1L0000010000047598_35356" onclick=
"rptlist(this);" onmouseout="wschk(0);" onmouseover=
"wschk(1);" type="checkbox" /> <span class="ul" onclick=
"nf('0000047598_35356');" onmouseout="pcls(this);"
onmouseover="ws(this);">Made to Order Deli Core</span>
</div>
</td>
<td class="price"></td>
</tr>
<tr class="lun">
<td class="station"> </td>
<td class="menuitem">
<div class="menuitem">
<input class="chk" id="S1L0000020000046033_63436" onclick=
"rptlist(this);" onmouseout="wschk(0);" onmouseover=
"wschk(1);" type="checkbox" /> <span class="ul" onclick=
"nf('0000046033_63436');" onmouseout="pcls(this);"
onmouseover="ws(this);">Chicken Caesar Wrap</span>
</div>
</td>
<td class="price"></td>
</tr>
<tr class="lun">
<td colspan="3" style="height:3px;"></td>
</tr>
<tr class="lun">
<td colspan="3" style="background-color:#c0c0c0; height:1px;"></td>
</tr>
<tr class="lun">
<td class="station"> Dessert</td>
<td class="station"> </td>
<td class="menuitem">
<div class="menuitem">
<input class="chk" id="S1L0000020000046033_63436" onclick=
"rptlist(this);" onmouseout="wschk(0);" onmouseover=
"wschk(1);" type="checkbox" /> <span class="ul" onclick=
"nf('0000046033_63436');" onmouseout="pcls(this);"
onmouseover="ws(this);">Chicken Caesar Wrap</span>
</div>
</td>
</tr>
</table>
</body>
</html>
Here is the code I have, I want just the items under the deli section, and normally I won't know how many there are is there a way to do this?
soup = BeautifulSoup(open("upperMenu.html"))
title = soup.find('td', class_='station').text.strip()
spans = soup.find_all('span', class_='ul')[:2]
but this only works if there are two items, how can I have it work if the number of items is unknown?
Thanks in advance
You can use the text attribute in find_all function to 1. find all the rows whose station column contains the substring Deli.. 2. Loop through every row and find the spans within that row whose class is ul.
import re
soup = BeautifulSoup(text)
tds_deli = soup.find_all(name='td', attrs={'class':'station'}, text=re.compile('Deli'))
for td in tds_deli:
try:
tr = td.find_parent()
spans = tr.find_all('span', {'class':'ul'})
for span in spans:
# do something
print span.text
print '------------one row -------------'
except:
pass
Sample Output in this case:
Made to Order Deli Core
------------one row -------------
Not sure if I am understanding the problem correctly but I think my code might help you get started.