当 HTML 代码不一致时,如何使用 python 中的 bs4 识别正确的 td 标签

How can I identify the correct td tag using bs4 in python when HTML code is inconsistent

我在 Python 中使用 BeautifulSoup4 来解析一些 HTML 代码。我已经设法深入到正确的 table 并识别 td 标签,但我面临的问题是标签中的样式属性应用不一致,它正在完成获取正确 td 的任务标记一个真正的挑战。

我试图拉取的数据是一个日期字段,但在任何时候都会有多个使用 CSS 隐藏的 td 标签(可见的内容取决于在其他地方选择的选项值HTML 代码)。

实例:

<td style="display: none;">01/03/2016</td>
<td style="display: table-cell;">27/10/2015</td> <-- this is the tag I want

<td style="display:none">23/02/2016</td>
<td style="">09/05/2011</td> <-- this is the tag I want
<td style="display: none;">29/03/2011</td>
<td style="display:none">19/10/2010</td>

<td>27/10/2015</td> <-- this is the tag I want
<td style="display: none">01/03/2016</td>
<td style="display: none">22/03/2016</td>

<td style="display:none">11/04/2015</td>
<td style="display: table-cell;">02/02/2016</td> <-- this is the tag I want
<td style="display: none">18/10/2013</td>

我如何 exclude/remove 不正确的项目(具有 display:nonedisplay: none 的样式)给我留下我真正想要的项目?

使用列表 comp 过滤 tds,仅当 td 在集合中没有样式属性时才保留 {"display:none", "display: none;","display: none;","display: none"}:

In [8]: h1 = """"<td style="display: none;">01/03/2016</td>
   ...: <td style="display: table-cell;">27/10/2015</td>"""

In [9]: h2 = """"<td style="display:none">23/02/2016</td>
   ...: <td style="">09/05/2011</td> <-- this is the tag I want
   ...: <td style="display: none;">29/03/2011</td>
   ...: <td style="display:none">19/10/2010</td>"""

In [10]: h3 = """"<td>27/10/2015</td> <-- this is the tag I want
   ....: <td style="display: none">01/03/2016</td>
   ....: <td style="display: none">22/03/2016</td>"""

In [11]: h4 = """<td style="display:none">11/04/2015</td>
   ....: <td style="display: table-cell;">02/02/2016</td> <-- this is the tag I want
   ....: <td style="display: none">18/10/2013</td>"""

In [12]: ignore = {"display:none", "display: none;", "display: none;", "display: none"}

In [13]: for html in [h1, h2, h3, h4]:
   ....:         soup = BeautifulSoup(html, "html.parser")
   ....:         print([td for td in soup.find_all("td") if not td.get("style") in ignore])
   ....:     
[<td style="display: table-cell;">27/10/2015</td>]
[<td style="">09/05/2011</td>]
[<td>27/10/2015</td>]
[<td style="display: table-cell;">02/02/2016</td>]