在beautifulSoup中按位置选择多个标记

2024-10-08 18:23:33 发布

您现在位置:Python中文网/ 问答频道 /正文

考虑以下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)")

Tags: andofcomidhttptitleexamplehtml
2条回答

如果您的解决方案不是围绕CSS类,那么最好使用soup.find_all()

needed_a_tags = [tag for i, tag in enumerate(soup.find_all('a')) if i in [1,2,4]]

将CSS选择器与逗号", ":'a:nth-child(2), a:nth-child(3), a:nth-child(5)'一起使用:

import requests
from bs4 import BeautifulSoup

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 = BeautifulSoup(html_doc, 'html.parser')

a2, a3, a5 = soup.select('a:nth-child(2), a:nth-child(3), a:nth-child(5)')

print(a2)
print(a3)
print(a5)

印刷品:

<a class="sister" href="http://example.com/tillie" id="link3">Millie</a>
<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>
<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>

更多信息:CSS Selectors Reference

相关问题 更多 >

    热门问题