我正在尝试使用 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 fiddle 中):
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")
最佳答案
尝试使用此选择器:
targetText2 = text.select(".Book-Title- + .Text")
或在波浪号字符和同级字符之间添加空格:
targetText2 = text.select(".Book-Title- ~ .Text")
关于python - Beautiful Soup 4 CSS 同级选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22465943/