如何在Beautifulsoup的输出中获取id号?

2024-05-02 07:38:56 发布

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

我试图从字符串中获取一个特定的ID,我尝试了做replace(),我尝试了一些使用regex的方法,但似乎无法获得它。我怎么才能拿到那个身份证号码?而且数字显示两次,所以我只需要一个

我无法让它与正则表达式一起工作,因为它实际上不是字符串,而是类型“<;class'bs4.element.Tag'>;”

输出如下

<span class="New_Link" id="tid_5785847"><a href="showthread.php?tid=5785847">Some text here?</a></span>

1条回答
网友
1楼 · 发布于 2024-05-02 07:38:56

所以,这是我的变体

from bs4 import BeautifulSoup
html = '<span class="New_Link" id="tid_5785847"><a href="showthread.php? 
tid=5785847">Some text here?</a></span>'

soup = BeautifulSoup(html, 'html.parser')
span_attribute = soup.find('span')
id_value = span_attribute.get('id')  # it is your ID from id="tid_5785847"
id_value = id_value.replace('tid_', '')  # replace tid_
print(id_value)  # print only 5785847

相关问题 更多 >