【问题标题】:Parsing changing tags BeautifulSoup解析更改标签 BeautifulSoup
【发布时间】:2013-07-02 00:50:37
【问题描述】:

如果我的标签不断变化如下:

<tr id="CN13FUT">
<tr id="CU13FUT">
<tr id="CZ13FUT">
<tr id="CH14FUT">
[...]

如何在使用 BeautifulSoup 时阅读此内容? 这是我需要帮助的:

table = BeautifulSoup(page)
for tr in table.findAll('tr', attrs = {'id': 'something_here'))
   print tr

我不想只使用table.findAll('tr'),因为可能还有其他我不想要的tr 标签,我只想按照上面的格式显示。

【问题讨论】:

  • 所有trs(你需要的)都有id吗?它们总是以 C 开头吗?

标签: python beautifulsoup


【解决方案1】:

您可以使用正则表达式模式来指定您想要的 &lt;tr&gt;s:

import bs4 as bs
import re

doc = '''<tr id="CN13FUT">
    <tr id="CU13FUT">
    <tr id="CZ13FUT">
    <tr id="CH14FUT">
    <tr id="ButNotThis">
   '''
table = bs.BeautifulSoup(doc)
for tr in table.findAll(id=re.compile(r'CN13|CU13|CZ13|CH14')):
    print(tr)

产量

<tr id="CN13FUT">
</tr>
<tr id="CU13FUT">
</tr>
<tr id="CZ13FUT">
</tr>
<tr id="CH14FUT">
</tr>

【讨论】:

  • 但是如果我不知道&lt;tr&gt; id=... 有多少标签怎么办?也许阅读所有tr标签并解析正确的标签会更容易。
  • 我的解决方案不需要您知道标签的数量。它仅用于显示基于使用正则表达式模式选择所需的tr 标记的答案的form。您从未说明选择所需 tr 标记的标准,所以我假设您知道如何形成正确的正则表达式模式。如果您不这样做,则需要说明标准。
【解决方案2】:

如果所有id属性都以“FUT”结尾,那么

for tr in table.findAll(id=re.compile('FUT$')):
    print(tr)
    print(tr['id']) # to print the id attributes

如果所有id属性的长度相同(7),那么

for tr in table.findAll('tr', id=lambda x: x and len(x)==7):
    print(tr['id']) # to print the id attributes

【讨论】:

    猜你喜欢
    • 2021-03-20
    • 2016-12-30
    • 1970-01-01
    • 2017-09-24
    • 2013-03-20
    • 2012-05-22
    • 2017-10-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多