【问题标题】:split two tags and append them separately in bs4 python拆分两个标签并在 bs4 python 中分别附加它们
【发布时间】:2018-11-07 08:32:02
【问题描述】:

我有一个TR[2],它是动态的,我试着像这样得到它:

self.soup.select("#detail > tbody > tr > td:nth-of-type(2)")

我希望所有td[3] 都在其中,它们以这种方式是动态的: 他们可能只有字符串或字符串和<a href> 现在我想将字符串拆分为某个变量,并将该<a> 标记的“字符串”拆分为另一个,但重要的是td 没有<a>我希望它附加“无”,因为两个变量应该具有相同的长度和索引,以便正确“压缩”它们以供进一步使用。 这是一些例子:

<td class='bolt'>
  "the text I want"
  <br>
  <a href='Javascript:void(0);'>the other text i want</a>
</td>

当它们附加到 var 时应该如下所示:

event = ["the text I want"]
vessel = ["the other text i want"]

还有另一个“可能的”td:

<td class='bolt'>
   "another string we need"
</td>

以及最终结果:

event = ["the text I want","another string we need"]
vessel = ["the other text i want", None(or empty),]

【问题讨论】:

    标签: python parsing web-scraping beautifulsoup web-crawler


    【解决方案1】:

    如果可以有一个或两个文本节点(如问题所述),您可以使用

    vessel = []
    event = []
    for td in self.soup.select("#detail > tbody > tr > td:nth-of-type(2)"):
        event.append([i.strip() for i in td.strings if i.strip()][0])
        vessel.append(([i.strip() for i in td.strings if i.strip()] + [None])[1])
    
    print(event)
    ['"the text I want"', '"another string we need"']
    print(vessel)
    ['the other text i want', None]
    

    如果有更复杂的情况,请告诉我

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-23
      • 1970-01-01
      • 2015-03-01
      • 2021-02-08
      • 2022-10-22
      • 1970-01-01
      相关资源
      最近更新 更多