标签:
BeautifulSoup支持大部分的CSS选择器 ,在Tag或BeautifulSoup对象的.select() 方法中传入字符串参数,即可使用CSS选择器的语法找到tag:
soup.select("title")
soup.select("p nth-of-type(3)")
soup.select("body a")
body下的直接子节点a
soup.select("body > a")
soup.select("p > a:nth-of-type(2)")
soup.select("p > #link1")
soup.select("#link1 ~ .sister")
soup.select("#link1 + .sister")
soup.select(".sister")
# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
# <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
# <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
soup.select("[class~=sister]")
# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
# <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
# <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
通过tag的id查找:
soup.select("#link1")
# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>]
soup.select("a#link2")
# [<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]
通过是否存在某个属性来查找:
soup.select(‘a[href]‘)
# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
# <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
# <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
通过属性的值来查找:
soup.select(‘a[href="http://example.com/elsie"]‘)
# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>]
soup.select(‘a[href^="http://example.com/"]‘)
# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
# <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
# <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
soup.select(‘a[href$="tillie"]‘)
# [<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
soup.select(‘a[href*=".com/el"]‘)
# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>]
通过语言设置来查找:
multilingual_markup = """
<p lang="en">Hello</p>
<p lang="en-us">Howdy, y‘all</p>
<p lang="en-gb">Pip-pip, old fruit</p>
<p lang="fr">Bonjour mes amis</p>
"""
multilingual_soup = BeautifulSoup(multilingual_markup)
multilingual_soup.select(‘p[lang|=en]‘)
# [<p lang="en">Hello</p>,
# <p lang="en-us">Howdy, y‘all</p>,
# <p lang="en-gb">Pip-pip, old fruit</p>]
http://www.w3school.com.cn/cssref/css_selectors.ASP
标签:
原文地址:http://www.cnblogs.com/newpython/p/5935061.html