My HTML :
<table cellspacing="0" cellpadding="2" rules="all" border="1" id="branchTable" width="100%">
<tr class="TitleTable">
<th scope="col" width="250"><b>Branch Name</b></th><th scope="col" width="35%"><b>Branch Date</b></th><th scope="col" width="35%"><b>Branch Origin</b></th>
</tr><tr class="RowSet">
<td><a class="blue" href="javascript: OpenWindow('/home/data/files/fetchRecord.php?fileID=342')">SFO Branch</a></td><td class="red">03/16/2012</td><td class="red"> </td>
</tr><tr class="RowSet">
<td><a class="blue" href="javascript: OpenWindow('/home/data/files/fetchRecord.php?fileID=884')">LAX Branch</a></td><td class="red">03/16/2012</td><td class="red">06/16/1985</td>
</tr><tr class="RowSet">
<td><a class="blue" href="javascript: OpenWindow('/home/data/files/fetchRecord.php?fileID=83')">DC Branch</a></td><td class="red">03/16/2012</td><td class="red"> </td>
</tr>
</table>
My Code so far :
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(pageSource)
table = soup.find("table", id = "branchTable")
rows = table.findAll("tr", {"class":"RowSet"})
data = [[td.findChildren(text=True) for td in tr.findAll("td")] for tr in rows]
print data
Output :
SFO Branch 03/16/2012
LAX Branch 03/16/2012 06/16/1985
DC Branch 03/16/2012
Desired :
I would like to grab the data enclosed in the tags as well as the ID (fetchRecord.php?fileID= 342 ) . Not sure how to fetch that value. BeautifulSoup or Regex, please help. Thanks!
You can use a regex to parse the href
but I was too lazy to write one. See href_parse
below for the proper way to parse a query string after retrieving the URI:
from urlparse import urlparse
from urlparse import parse_qs
def href_parse(value):
if (value.startswith('javascript: OpenWindow('') and
value.endswith('')'):
begin_length = len('javascript: OpenWindow('')
end_length = len('')')
file_location = value[begin_length:-end_length]
query_string = urlparse(file_location).query
query_dict = parse_qs(query_string)
return query_dict.get('fileId', None)
href_data = [[href_parse(td.find('a', attrs={'class': 'blue'})['href'])
for td in tr.findAll("td")]
for tr in rows]
print href_data
How about this
import re
urlRE = re.compile('javascript: OpenWindow\(\'(.*)#39;\)')
...
urlMat = urlRE.match(value)
if urlMat:
url = urlMat.groups()[0]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.