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

标签 python html beautifulsoup

我正在 Python 中使用 BeautifulSoup4 来解析一些 HTML 代码。我已经设法深入到正确的表并识别 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>

如何排除/删除不正确的项目(其样式为 display:nonedisplay: none),以便留下我真正想要的项目?

最佳答案

使用列表组合过滤 td,仅当 td 在集合中没有样式属性时才保留 {"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>]

关于python - 当HTML代码不一致时,如何在python中使用bs4识别正确的td标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38927775/

相关文章:

python - 无法在 pygame 中在全屏和窗口模式之间切换

python - 如何为 functools.lru_cache 创建别名以进行内存?

python - 使用 del 和切片是否会先创建一个新对象,然后再删除?会就位吗?

html - Flexbox 不遵守 overflow-x : hidden on body (Safari/iOS webkit)

python - 如何使用漂亮的汤在 XHTML 中提取没有样式键的内联 CSS 样式

python - 使用 groupby 和 transform 每周获取 idxmax

javascript - 将鼠标悬停在列表上时显示文本

python - 如何在html中使用正则表达式或其他方式在python中删除<p>标签下的属性?

python - 如何使用 beautiful soup 将爬取数据上传到 python 中的 AZURE BLOB STORAGE 中?

html - HTML+CSS 中的时间线示例,如 Facebook 的时间线