繁体   English   中英

使用 beautifulsoup 抓取 HTML 网站 ID 的特定部分

[英]Scraping specific part of HTML website ID using beautifulsoup

我试图刮掉下面 html (1217428) 的 id,而不刮掉 id 标签的 rest,但我不知道如何只隔离所需的部分。

<td class="pb-15 text-center">
<a href="#" id="1217428_1_10/6/2020 12:00:00 AM" class="slotBooking">
    8:15 AM ✔ 
</a>
</td>

到目前为止,我想出了这个:

lesson_id = [] # I wish to fit the lesson id in this list
soup = bs(html, "html.parser")
slots = soup.find(attrs={"class" : "pb-15 text-center"})
tag = slots.find("a")
ID = tag.attrs["id"]
print (ID)

但这仅允许我将其作为 output 接收:

1217428_1_10/6/2020 12:00:00 AM

有什么办法可以编辑我的代码,使 output 成为:

1217428

我也尝试过使用正则表达式:

lesson_id = []
soup = bs(html, "html.parser")
slots = soup.find(attrs={"class" : "pb-15 text-center"})
tag = slots.find("a")
ID = tag.attrs["id"]
lesson_id.append(ID(re.findall("\d{7}")))

但我收到此错误:

TypeError: findall() missing 1 required positional argument: 'string'

您可以按如下方式简单地拆分刺痛:

id_list = ID.split('_',1)
#will give you ['1217428', '1_10/6/2020 12:00:00 AM']
id = id_list[0] # which is '1217428'

您也可以使用正则表达式:

match = re.search(r'\d{1,}',ID)
id = match.group() # '1217428'

我认为你可以通过用“_”分割 id 并使用第一部分来解决你的问题。 (这是我从你上面的例子中理解的):

lesson_id = [] # I wish to fit the lesson id in this list
soup = bs(html, "html.parser")
slots = soup.find(attrs={"class" : "pb-15 text-center"})
tag = slots.find("a")
ID = tag.attrs["id"]
if ID:
    ID = ID.split("_")[0]
print (ID)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM