2 回答

TA貢獻(xiàn)1936條經(jīng)驗(yàn) 獲得超7個(gè)贊
希望,并非總是如此,id 應(yīng)該是唯一的含義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個(gè)孩子
print(soup.select_one('#productTitle span:nth-child(2)').text)
或者
print(soup.select_one('#productTitle span:nth-child(even)').text)
甚至是一個(gè)直接的兄弟姐妹組合來(lái)獲得span孩子a
print(soup.select_one('#productTitle a + span').text)
或鏈接 next_sibling
print(soup.select_one('#productTitle a').next_sibling.next_sibling.text)

TA貢獻(xiàn)1827條經(jīng)驗(yàn) 獲得超9個(gè)贊
h1這會(huì)在標(biāo)簽中獲取您需要的所有字段:
蟒蛇代碼:
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))
添加回答
舉報(bào)