簡體   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