使用 BeautifulSoup 获取第 n 个元素

Posted

技术标签:

【中文标题】使用 BeautifulSoup 获取第 n 个元素【英文标题】:Getting the nth element using BeautifulSoup 【发布时间】:2012-02-02 04:56:43 【问题描述】:

我想从一张大表中读取第 5、10、15、20 行...使用 BeautifulSoup。我该怎么做呢? findNextSibling 和递增计数器是否可行?

【问题讨论】:

【参考方案1】:

您还可以使用findAll 获取列表中的所有行,然后使用切片语法访问您需要的元素:

rows = soup.findAll('tr')[4::5]

【讨论】:

这很干净。注意 find all 方法返回一个数组,所以这很棒。 为什么切片可以工作而单个索引不起作用【参考方案2】:

如果您知道要选择的行号,则可以在美丽的汤中使用select 轻松完成此操作。 (注意:这是在 bs4 中)

row = 5
while true
    element = soup.select('tr:nth-of-type('+ row +')')
    if len(element) > 0:
        # element is your desired row element, do what you want with it 
        row += 5
    else:
        break

【讨论】:

我遇到了与 OP 类似的问题,但虽然这看起来更简洁,但它并没有让我从“元素”中提取任何数据,任何 findAll 搜索只会导致整个页面【参考方案3】:

作为一般解决方案,您可以将表格转换为嵌套列表并进行迭代...

import BeautifulSoup

def listify(table):
  """Convert an html table to a nested list""" 
  result = []
  rows = table.findAll('tr')
  for row in rows:
    result.append([])
    cols = row.findAll('td')
    for col in cols:
      strings = [_string.encode('utf8') for _string in col.findAll(text=True)]
      text = ''.join(strings)
      result[-1].append(text)
  return result

if __name__=="__main__":
    """Build a small table with one column and ten rows, then parse into a list"""
    htstring = """<table> <tr> <td>foo1</td> </tr> <tr> <td>foo2</td> </tr> <tr> <td>foo3</td> </tr> <tr> <td>foo4</td> </tr> <tr> <td>foo5</td> </tr>  <tr> <td>foo6</td> </tr>  <tr> <td>foo7</td> </tr>  <tr> <td>foo8</td> </tr>  <tr> <td>foo9</td> </tr>  <tr> <td>foo10</td> </tr></table>"""
    soup = BeautifulSoup.BeautifulSoup(htstring)
    for idx, ii in enumerate(listify(soup)):
        if ((idx+1)%5>0):
            continue
        print ii

运行那个...

[mpenning@Bucksnort ~]$ python testme.py
['foo5']
['foo10']
[mpenning@Bucksnort ~]$

【讨论】:

【参考方案4】:

另一种选择,如果您更喜欢原始 html...

"""Build a small table with one column and ten rows, then parse it into a list"""
htstring = """<table> <tr> <td>foo1</td> </tr> <tr> <td>foo2</td> </tr> <tr> <td>foo3</td> </tr> <tr> <td>foo4</td> </tr> <tr> <td>foo5</td> </tr>  <tr> <td>foo6</td> </tr>  <tr> <td>foo7</td> </tr>  <tr> <td>foo8</td> </tr>  <tr> <td>foo9</td> </tr>  <tr> <td>foo10</td> </tr></table>"""
result = [html_tr for idx, html_tr in enumerate(soup.findAll('tr')) \
     if (idx+1)%5==0]
print result

运行那个...

[mpenning@Bucksnort ~]$ python testme.py
[<tr> <td>foo5</td> </tr>, <tr> <td>foo10</td> </tr>]
[mpenning@Bucksnort ~]$

【讨论】:

【参考方案5】:

以下是使用gazpacho 抓取this Wikipedia 页面上每5 个分发链接的方法:

from gazpacho import Soup

url = "https://en.wikipedia.org/wiki/List_of_probability_distributions"
soup = Soup.get(url)

a_tags = soup.find("a", "href": "distribution")
links = ["https://en.wikipedia.org" + a.attrs["href"] for a in a_tags]

links[4::5] # start at 0,1,2,3,**4** and stride by 5

【讨论】:

以上是关于使用 BeautifulSoup 获取第 n 个元素的主要内容,如果未能解决你的问题,请参考以下文章

BeautifulSoup文档1-简介安装和使用

如何从 BeautifulSoup ( Python ) 中的表中获取第一个子表行

我如何从 BeautifulSoup 中获取 CData

第3关 BeautifulSoup实践

python3实践-从网站获取数据(Carbon Market Data-GD) (bs4/Beautifulsoup)

BeautifulSoup文档3-详细方法 | 如何对文档树进行遍历?