码迷,mamicode.com
首页 > Web开发 > 详细

css selector

时间:2016-10-07 01:08:53      阅读:215      评论:0      收藏:0      [点我收藏+]

标签:


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

css selector

标签:

原文地址:http://www.cnblogs.com/newpython/p/5935061.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!