简体   繁体   中英

How to parse this HTML table with BeautifulSoup and Regex?

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(&#39;/home/data/files/fetchRecord.php?fileID=342&#39;)">SFO Branch</a></td><td class="red">03/16/2012</td><td class="red">&nbsp;</td>
            </tr><tr class="RowSet">
                <td><a class="blue" href="javascript: OpenWindow(&#39;/home/data/files/fetchRecord.php?fileID=884&#39;)">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(&#39;/home/data/files/fetchRecord.php?fileID=83&#39;)">DC Branch</a></td><td class="red">03/16/2012</td><td class="red">&nbsp;</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  &nbsp;
LAX Branch  03/16/2012  06/16/1985
DC Branch   03/16/2012  &nbsp;

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(&#39;') and 
        value.endswith('&#39;)'):
        begin_length = len('javascript: OpenWindow(&#39;')
        end_length = len('&#39;)')
        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;(.*)#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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM