python - Beautiful Soup 4 CSS 选择器的工作方式与教程显示的不同

标签 python html css css-selectors beautifulsoup

我运行了 [Beautiful Soup 4 教程页面][1] 中的 CSS 选择器示例 代码,但结果不同,有些给出了正确的结果,有些则没有。在网站上,他们说它应该在 Python 2.7 和 3 中以相同的方式工作。我有 Python 2.7 并且安装 Beautiful Soup 4。有人遇到同样的问题吗?

from bs4 import BeautifulSoup
import urllib2

html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>

<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>

<p class="story">...</p>
"""

soup = BeautifulSoup(html_doc)

我的测试(当然我在教程中使用相同的 html 文档):

soup.select("#link1 ~ .sister")
[]

他们的测试:

soup.select("#link1 ~ .sister")
# [<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
#  <a class="sister" href="http://example.com/tillie"  id="link3">Tillie</a>]

Click Here to See

最佳答案

我已经解决了你的问题。您使用的 BeautifulSoup 版本早于 4.3.2。

我刚刚安装了 4.1.2,并运行了您的代码。我有同样的问题,我得到一个空列表,现在我已经将它更新到 4.3.2,我又得到了 sibling 的列表。

可以通过 pip 安装它,但您也可以获得最新的 version from Pypi并下载。

关于python - Beautiful Soup 4 CSS 选择器的工作方式与教程显示的不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19516341/

相关文章:

javascript - 选择具有其他类名称的附近表行并切换类

html - 移动优先响应式网页设计和响应式图像问题

python - 从 C++ 自动生成 python 模块的 Tensorflow 源代码

Python正则表达式捕获单个字符字母

python - 将 Python 侧模块从 Github 安装到 Anaconda

python - 为什么我的删除按钮没有删除我的数据库对象? Django

php - 如何通过连接输出用户信息到表中

php - wordpress 主题中 <em> 的未知输出

html - 我无法显示基于 div 的菜单

css - 填充此 div 的最佳方法是什么?