【问题标题】:Beautiful Soup 4 CSS sibling selectorBeautiful Soup 4 CSS 兄弟选择器
【发布时间】:2014-04-23 08:11:57
【问题描述】:

我正在尝试使用 Beatiful Soup 4 abd Python 2.7 解析从 InDesign 文档导出的一些 HTML。我正在尝试使用 CSS 兄弟选择器来查找特定标签。我可以通过 CSS 选择器选择其兄弟标签,然后使用 Beautiful Soup find_next_sibling() 方法来访问我想要的标签,但我不能直接通过 CSS 选择器选择它。

当我在纯 CSS/JS (http://jsfiddle.net/Sj63x/1/) 中尝试时,我已经验证了选择器本身是有效的。我也尝试过使用 Beautiful Soup 主页上推荐的所有三个解析器。

相关代码贴在下面(文字在JS小提琴中):

text = BeautifulSoup(text)

'''this finds the sibling'''
sibling = text.select(".Book-Title-") 
print(sibling[0].string)

'''this finds the sibling I am looking for'''
targetText = sibling[0].find_next_sibling()
print(targetText.string)

'''This should find the same text but returns an empty list'''
targetText2 = text.select(".Book-Title- ~.Text")
print(targetText2)

'''Other attempted variations - also return empty lists'''
targetText3 = text.select(".Book-Title- ~ .Text")
targetText4 = text.select(".Book-Title- + .Text")

【问题讨论】:

    标签: python python-2.7 beautifulsoup


    【解决方案1】:

    尝试使用此选择器:

    targetText2 = text.select(".Book-Title- + .Text")
    

    或在波浪号和兄弟之间添加一个空格:

    targetText2 = text.select(".Book-Title- ~ .Text")
    

    【讨论】:

    • 谢谢。两者都返回空列表,就像原始选择器一样。我已将它们添加到问题中。
    • 奇怪,我自己还没有测试过代码。您正在运行最新版本的 beautifulsoup 吗?旧版本中的 CSS 选择器似乎存在一些问题(请参阅stackoverflow.com/questions/19516341/…
    • 如果你想打印这个:[<span class="Text"> (December 1982)</span>] 那么 HAL 的第二行可以正常工作。
    • 这是 BeautifulSoup 版本 - apt-get 提供的版本是旧版本。通过 pip 卸载和更新工作。
    猜你喜欢
    • 1970-01-01
    • 2012-08-02
    • 2011-12-13
    • 1970-01-01
    • 1970-01-01
    • 2014-02-15
    • 1970-01-01
    • 1970-01-01
    • 2021-03-06
    相关资源
    最近更新 更多