python - Beautiful Soup 4 CSS 同级选择器

标签 python python-2.7 beautifulsoup

我正在尝试使用 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/

相关文章:

python - LSTM 的输出不会因不同的输入而改变

python - 适用于 Windows 10 的 Anaconda (Python 2.7) 出现内核错误。Spyder IDE 控制台错误

python - Docker 从密码数据库获取用户名时出错

python - Appengine 队列桶如何填充?

Python BeautifulSoup - 获取 Div Select Option 中的值

python - BeautifulSoup soup.select 切断子标签

python - 属性错误: 'NavigableString' object has no attribute 'find_all' (NameError)

python - 用特定键优雅地替换嵌套 JSON 中的值的最短方法

python - 具有 int 值的 SQLAlchemy order_by 字符串列

Python:用字典键值对中的值替换值