简体   繁体   English

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

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

I am trying to scrape the id of the below html (1217428), without scraping the rest of the id tag, but I have no clue how to isolate only the desired portion.我试图刮掉下面 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>

So far I have come up with this:到目前为止,我想出了这个:

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)

But this only allows me to receive this as an output:但这仅允许我将其作为 output 接收:

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

Is there any way I could edit my code such that the output would be:有什么办法可以编辑我的代码,使 output 成为:

1217428

I have also tried using regex with this:我也尝试过使用正则表达式:

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

But I receive this error:但我收到此错误:

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

You can simply split the sting as follows:您可以按如下方式简单地拆分刺痛:

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

You can use Regular Expression as well:您也可以使用正则表达式:

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

I think this you can solve your problem by splitting the id with "_" and using the first part.我认为你可以通过用“_”分割 id 并使用第一部分来解决你的问题。 (this is what I understand from your above example): (这是我从你上面的例子中理解的):

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