1

我正在尝试抓取以下 html (1217428) 的 id,而不抓取 id 标签的其余部分,但我不知道如何仅隔离所需的部分。

<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)

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

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

有什么方法可以编辑我的代码,使输出为:

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'
4

2 回答 2

1

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

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'
于 2020-04-08T08:08:36.917 回答
1

我认为你可以通过用“_”分割 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)
于 2020-04-08T08:09:10.850 回答