【问题标题】:How can I select every nth child in BeautifulSoup?如何在 BeautifulSoup 中选择每第 n 个孩子?
【发布时间】:2018-07-03 23:27:09
【问题描述】:

在我的下表中,我已抓取项目 1-4 并将它们存储在名为标题的变量中。

我还想选择值 1-4 并将它们存储在一个名为列的变量中,无论如何都要选择每一秒。像

columns = boxinfo.find_all("td").nthChild(2)

我正在从中抓取的表结构

<div class="box1">

<table class="table1">

<tr><td class="label">Item1</td><td>Value1</td></tr>

<tr><td class="label">Item2</td><td>Value2</td></tr>

<tr><td class="label">Item3</td><td>Value3</td></tr>

<tr><td class="label">Item4</td><td>Value4</td></tr>

</table>

</div>

代码

#Find our information
boxinfo = soup.find("div", {"id": "box1"})
headings = boxinfo.find_all("td", {"class": "label"})
columns = boxinfo.find_all("td").nthChild(2) #This does not work :(

【问题讨论】:

  • 纯美的汤是你做不到的,但你可以在搜索中添加过滤功能。但最简单的是columns = [column for i, column in enumerate(boxinfo.find_all("td")) if i%2 == 1]
  • @bobrobbob 我如何获得以下html元素,因为我在python中使用带有beautifulsoup的js来获取它-- document.querySelector('body > table > tbody > tr > td > table > tbody > tr:nth-child(2) > td:nth-child(2) > div:nth-child(3) > table > tbody > tr:nth-child(11) > td > table > tbody > tr:nth- child(4) > td:nth-child(5) > input[type="hidden"]:nth-child(1)').getAttribute("name")

标签: python beautifulsoup


【解决方案1】:

如果您尝试提取所有值,那么您可以让 BeautifulSoup 返回所有项目,然后 Python 可以过滤您想要的值。例如:

from bs4 import BeautifulSoup

html = """<div class="box1">
<table class="table1">
<tr><td class="label">Item1</td><td>Value1</td></tr>
<tr><td class="label">Item2</td><td>Value2</td></tr>
<tr><td class="label">Item3</td><td>Value3</td></tr>
<tr><td class="label">Item4</td><td>Value4</td></tr>
</table>
</div>"""

soup = BeautifulSoup(html, "html.parser")
div = soup.find("div", class_="box1")
values = []

for tr in div.find_all('tr'):
    values.append(tr.find_all("td")[1].text)

print(values)

给你一个值列表:

['Value1', 'Value2', 'Value3', 'Value4']

或者,如果您想要一个包含所有数据作为列的列表:

soup = BeautifulSoup(html, "html.parser")
div = soup.find("div", class_="box1")
columns = []

for tr in div.find_all('tr'):
    columns.append([td.text for td in tr.find_all("td")])

columns = list(zip(*columns))    

print(columns)
print(columns[1])  # display the 2nd column

给你:

[('Item1', 'Item2', 'Item3', 'Item4'), ('Value1', 'Value2', 'Value3', 'Value4')]
('Value1', 'Value2', 'Value3', 'Value4')

list(zip(*columns)) 是一种将行列表转换为列列表的方法。

【讨论】:

  • @Martin Evans 如何在 python 中使用带有 beautifulsoup 的 js 获取以下 html 元素--document.querySelector('body > table > tbody > tr > td > table > tbody > tr:nth-child(2) > td:nth-child(2) > div:nth-child(3) > table > tbody > tr:nth-child(11) > td > table > tbody > tr:nth -child(4) > td:nth-child(5) > input[type="hidden"]:nth-child(1)').getAttribute("name")
  • @dpkrai96,如果你用一些代码创建一个新问题来显示问题会更容易。然后,您可以在您的问题下方用我的名字添加评论,我会看到的。
猜你喜欢
  • 1970-01-01
  • 2014-01-13
  • 2012-07-22
  • 1970-01-01
  • 1970-01-01
  • 2023-03-16
  • 2013-07-13
  • 1970-01-01
相关资源
最近更新 更多