考虑以下HTML:
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/tillie" class="sister" id="link3">Millie</a>
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</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 = bs4.BeautifulSoup(html_doc, 'html.parser')
如果我想要第二个a标签,我可以:
soup.select("a:nth-of-type(2)")
但是,如果我想选择第二、第三和第五个a标签,我该怎么做? 我试着用下面的方法,这给了我错误
soup.select("a:nth-of-type([2, 3, 5])")
soup.select("a:nth-of-type(2, 3, 5)")
如果您的解决方案不是围绕CSS类,那么最好使用
soup.find_all()
将CSS选择器与逗号
", "
:'a:nth-child(2), a:nth-child(3), a:nth-child(5)'
一起使用:印刷品:
更多信息:CSS Selectors Reference
相关问题 更多 >
编程相关推荐