我需要使用beautifulsouppython从没有内部标记数据的类标记中检索数据

2024-05-19 23:02:40 发布

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

我需要从检索数据伊克曼.lk“使用beautifulsouppython库。你知道吗

 <span class="t-small summary-count">  Showing 1-25 of 131 ads for <span>"Samsung Galaxy A5"</span>.</span>

我只需要得到“显示131广告1-25”部分使用Beautifulsoup库。 我试过了

    pgn = soup1.find("span", {"class": "t-small summary-count"}).text
    print(pgn)

但是它说“'NoneType'对象没有属性'text'”。 谢谢


Tags: of数据textforcountsummaryclasssmall
2条回答

如果我答对了问题,您需要在子标记之前从标记中获取初始文本。标签的子项在名为.contents的列表中可用。你知道吗

您可以使用.contents[0]

from bs4 import BeautifulSoup
html="""
<span class="t-small summary-count">  Showing 1-25 of 131 ads for <span>"Samsung Galaxy A5"</span>.</span>
"""
soup=BeautifulSoup(html,'html.parser')
pgn = soup.find("span", {"class": "t-small summary-count"})
print(pgn.contents)
print(pgn.contents[0])

输出

['  Showing 1-25 of 131 ads for ', <span>"Samsung Galaxy A5"</span>, '.']
  Showing 1-25 of 131 ads for 

您需要使用select找到<span> .... </span>,然后使用previousSibling在它前面获取文本 所有代码:

from bs4 import BeautifulSoup
html = ''' <span class="t-small summary-count">  Showing 1-25 of 131 ads for 
<span>"Samsung Galaxy A5"</span>.</span>
'''
soup = BeautifulSoup(html, 'lxml')
get_span = soup.find('span' , attrs={'class' : 't-small summary-count'})



for a in get_span.select('span'):
    print a.previousSibling

相关问题 更多 >