我从 [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>]