Python 我想找一个<;span>;位于a<;h1>;包含多个<;span>;标记并获取其中的文本

Python 我想找一个<;span>;位于a<;h1>;包含多个<;span>;标记并获取其中的文本,python,html,parsing,beautifulsoup,Python,Html,Parsing,Beautifulsoup,我想做的是选择第二个跨距并抓取它的文本来打印它。 下面是HTML代码和BeautifulSoup代码 #HTML code <h1 id="productTitle"> <a href="https://www.example.com/product/"> <span id="productBrand">BRAND</span> </a> <span>PRODUCT TITLE </s

我想做的是选择第二个跨距并抓取它的文本来打印它。 下面是HTML代码和BeautifulSoup代码

#HTML code

<h1 id="productTitle">
   <a href="https://www.example.com/product/">
       <span id="productBrand">BRAND</span>
   </a>
   <span>PRODUCT TITLE </span>
</h1>

这将获取
h1
标记中所需的所有字段:

Python代码:

from bs4 import BeautifulSoup
text = '''
<h1 id="productTitle">
   <a href="https://www.example.com/product/">
         <span id="productBrand">BRAND</span>
   </a>
         <span>PRODUCT TITLE </span>
</h1>
'''
soup = BeautifulSoup(text,features='html.parser')
#BeautifulSoup code

for h1 in soup.find_all('h1', id="productTitle"):
    spans = h1.find_all('span')
    print('productBrand  == > {}'.format(spans[0].text))
    print('productTitle  == > {}'.format(spans[1].text))
for h1 in soup.find_all('h1', id="productTitle"):
    for i,span in enumerate(h1.find_all('span')):
      print('span {} == > {}'.format(i,span.text))
演示:

希望,并非总是,id应该是唯一的,这意味着可能不需要查找所有的

对于bs4.7.1+,您可以使用:not排除具有id的子范围

from bs4 import BeautifulSoup as bs

html = '''<h1 id="productTitle">
   <a href="https://www.example.com/product/">
         <span id="productBrand">BRAND</span>
   </a>
         <span>PRODUCT TITLE </span>
</h1>
'''
soup = bs(html, 'lxml')
print(soup.select_one('#productTitle span:not([id])').text)

甚至是一个直接的兄弟组合,在子
a
a之后获得
span

print(soup.select_one('#productTitle a + span').text)
或者被锁在下一个兄弟姐妹身上

print(soup.select_one('#productTitle a').next_sibling.next_sibling.text)
print(soup.select_one('#productTitle span:nth-child(even)').text)
print(soup.select_one('#productTitle a + span').text)
print(soup.select_one('#productTitle a').next_sibling.next_sibling.text)