亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

我想找到一個 <span> 標簽,它位于包含多個 <span> 標簽的 <h1> 標簽內

我想找到一個 <span> 標簽,它位于包含多個 <span> 標簽的 <h1> 標簽內

阿晨1998 2022-06-22 18:12:29
我想要做的是選擇第二個跨度并抓住它的文本來打印它。下面是 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>#BeautifulSoup codefor h1 in soup.find_all('h1', id="productTitle"):    productTitle = h1.find('span').text    print(productTitle)
查看完整描述

2 回答

?
LEATH

TA貢獻1936條經驗 獲得超7個贊

希望,并非總是如此,id 應該是唯一的含義find_all可能不是必需的。


使用 bs4 4.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)

你也可以第n個孩子


print(soup.select_one('#productTitle span:nth-child(2)').text)

或者


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

甚至是一個直接的兄弟姐妹組合來獲得span孩子a


print(soup.select_one('#productTitle a + span').text)

或鏈接 next_sibling


print(soup.select_one('#productTitle a').next_sibling.next_sibling.text)


查看完整回答
反對 回復 2022-06-22
?
素胚勾勒不出你

TA貢獻1827條經驗 獲得超9個贊

h1這會在標簽中獲取您需要的所有字段:


蟒蛇代碼:


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))

使用 h1 獲取所有跨度:


for h1 in soup.find_all('h1', id="productTitle"):

    for i,span in enumerate(h1.find_all('span')):

      print('span {} == > {}'.format(i,span.text))


查看完整回答
反對 回復 2022-06-22
  • 2 回答
  • 0 關注
  • 164 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號