在bs4 python中拆分两个标记并分别附加它们

2024-06-14 18:09:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个TR[2]是动态的,我试着这样做:

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

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

<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),]

Tags: the字符串texteventstringanother动态class
1条回答
网友
1楼 · 发布于 2024-06-14 18:09:54

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

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]

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

相关问题 更多 >