请帮助用BeautifulSoup和lxml以Pythonic方式解析此HTML表格

0 投票
3 回答
2953 浏览
提问于 2025-04-16 10:23

我在网上查了很多关于BeautifulSoup的资料,有人建议用lxml作为BeautifulSoup的未来,这个说法听起来不错。不过,我在从网页上众多表格中解析出一个特定的表格时遇到了困难。

我对网页上三列数据感兴趣,这三列的行数会根据页面和检查的时间有所不同。如果能提供一个用BeautifulSoup和lxml的解决方案就太好了。这样我可以请管理员在开发机器上安装lxml。

期望的输出:

Website                    Last Visited          Last Loaded
http://google.com          01/14/2011 
http://stackoverflow.com   01/10/2011
...... more if present

下面是一个来自杂乱网页的代码示例:

<table border="2" width="100%">
  <tbody><tr>
    <td width="33%" class="BoldTD">Website</td>
    <td width="33%" class="BoldTD">Last Visited</td>
    <td width="34%" class="BoldTD">Last Loaded</td>
  </tr>
  <tr>
    <td width="33%">
      <a href="http://google.com"</a>
    </td>
    <td width="33%">01/14/2011
            </td>
    <td width="34%">
            </td>
  </tr>
  <tr>
    <td width="33%">
      <a href="http://stackoverflow.com"</a>
    </td>
    <td width="33%">01/10/2011
            </td>
    <td width="34%">
            </td>
  </tr>
</tbody></table>

3 个回答

3

这里有一个版本,它使用了elementtree这个库,以及它提供的有限的XPath功能:

from xml.etree.ElementTree import ElementTree

doc = ElementTree().parse('table.html')

for t in doc.findall('.//table'):
  # there may be multiple tables, check we have the right one
  if t.find('./tbody/tr/td').text == 'Website':
    for tr in t.findall('./tbody/tr/')[1:]: # skip the header row
      tds = tr.findall('./td')
      print tds[0][0].attrib['href'], tds[1].text.strip(), tds[2].text.strip()

结果:

http://google.com 01/14/2011
http://stackoverflow.com 01/10/2011 
4
>>> from lxml import html
>>> table_html = """"
...         <table border="2" width="100%">
...                       <tbody><tr>
...                         <td width="33%" class="BoldTD">Website</td>
...                         <td width="33%" class="BoldTD">Last Visited</td>
...                         <td width="34%" class="BoldTD">Last Loaded</td>
...                       </tr>
...                       <tr>
...                         <td width="33%">
...                           <a href="http://google.com"</a>
...                         </td>
...                         <td width="33%">01/14/2011
...                                 </td>
...                         <td width="34%">
...                                 </td>
...                       </tr>
...                       <tr>
...                         <td width="33%">
...                           <a href="http://stackoverflow.com"</a>
...                         </td>
...                         <td width="33%">01/10/2011
...                                 </td>
...                         <td width="34%">
...                                 </td>
...                       </tr>
...                     </tbody></table>"""
>>> table = html.fromstring(table_html)
>>> for row in table.xpath('//table[@border="2" and @width="100%"]/tbody/tr'):
...     for column in row.xpath('./td[position()=1]/a/@href | ./td[position()>1]/text() | self::node()[position()=1]/td/text()'):
...             print column.strip(),
...     print
... 
Website Last Visited Last Loaded
 http://google.com 01/14/2011 
 http://stackoverflow.com 01/10/2011 
>>> 

没错;)当然,你可以把你的值放到嵌套的列表或字典里,而不是打印出来;)

2

这里有一个使用HTMLParser的版本。我尝试过处理pastebin.com/tu7dfeRJ上的内容。这个版本能够处理meta标签和doctype声明,而这两个在ElementTree版本中出现了问题。

from HTMLParser import HTMLParser

class MyParser(HTMLParser):
  def __init__(self):
    HTMLParser.__init__(self)
    self.line = ""
    self.in_tr = False
    self.in_table = False

  def handle_starttag(self, tag, attrs):
    if self.in_table and tag == "tr":
      self.line = ""
      self.in_tr = True
    if tag=='a':
     for attr in attrs:
       if attr[0] == 'href':
         self.line += attr[1] + " "

  def handle_endtag(self, tag):
    if tag == 'tr':
      self.in_tr = False
      if len(self.line):
        print self.line
    elif tag == "table":
      self.in_table = False

  def handle_data(self, data):
    if data == "Website":
      self.in_table = 1
    elif self.in_tr:
      data = data.strip()
      if data:
        self.line += data.strip() + " "

if __name__ == '__main__':
  myp = MyParser()
  myp.feed(open('table.html').read())

希望这个版本能满足你的需求,你可以把它当作答案来接受。根据要求进行了更新。

撰写回答