我运行了 [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>]
最佳答案
我已经解决了你的问题。您使用的 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/