如何使用CSS访问BeautifulSoup中的嵌套HTMLelement

2024-05-14 10:56:56 发布

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

HTML是:

<span class="_hylizj6">
  <span class="_1m8bb6v">
    <span>Cena</span>
  </span>
  <span>233 zł</span>
</span>

使用BeautifulSoup和CSS选择器,如何访问“233zł”?你知道吗

我试过:

airbnb_soup.select('.hylizj6 span span')

但是不行,尽管

airbnb_soup.select('.hylizj6 span')

会得到“Cena”


Tags: html选择器selectcssclassspansoupairbnb
3条回答

当BeautifulSoap select()方法返回一个列表时,您需要使用索引访问它,在本例中为[0]。请参考Selecting nested element with beautiful soup。 此外,您还可以考虑find()或find\u all()方法,具体取决于需要解决的任务类型。你知道吗

基本上你做了什么(除了在'hylizj6'前面加下划线),然后要求紧接着的第二个跨度。你知道吗

>>> import bs4
>>> soup = bs4.BeautifulSoup(open('barciewicz.htm').read(), 'lxml')
>>> soup.select('._hylizj6  > span:nth-of-type(2)')[0].text
'233 zl'

有几种方法。如果HTML总是相同的,您可以使用

airbnb_soup.find_all('span')[-1].contents

相关问题 更多 >

    热门问题