Python BeautifulSoup 如何获取最新选择器的数据

发送 python HTTP 请求后,它的响应(数据)有一个 html 页面,其中包含许多 ABCD 块。这是一个片段


                   <tr>

                        <td class="success"></td>

                        <td class="truncate">ABCD</td>

                        <td>12/18/2018 21:45</td>

                        <td>12/18/2018 21:46</td>

                        <td>10</td>

                        <td>10</td>

                        <td>100.0</td>

                        <td><span class="label success">Success</span></td>

                        <td>SMS</td>

                        <td>

                            <a data-id="134717" class="btn" title="Go">View</a>

                        </td>

                    </tr>

我需要检索 ABCD 的最新数据 ID(在本例中为 134717,这个数字是动态的)。另请注意,有许多具有不同日期的 ABCD,我想要最新的 .


我可以使用正则表达式并逐行完成。但我认为最好用 BeautifulSoup 来做。


我试过这个它可以找到所有的 ABCD,但我不知道如何获得最新的:


    soup = BeautifulSoup(data, "html.parser")

    for i in soup.select("td.truncate"):

        #print(i.text)

        if i.text == "ABCD":

            print ("Got it ", i.text)

            id1 = soup.select_one("a.data-id")

            print (id1)

            parsed_url1 = urlparse(id1)


HUH函数
浏览 165回答 3
3回答

哈士奇WWW

您将需要dateutils 解析器。显然没有办法告诉哪个<td>有日期,所以你只需要遍历匹配的 tr 中的所有 td,并尝试解析日期时间,如果日期时间解析成功,只需将它附加到日期列表对于特定的 ID。在获得每个 ID 的所有日期后,您只需在它们上查找最新的日期即可。from dateutil import parser as du_parser&nbsp; &nbsp;&nbsp;from collections import defaultdictfrom bs4 import BeautifulSoup as BSdata = "<tr><td class=\"success\"></td><td class=\"truncate\">ABCD</td><td>12/18/2018 21:45</td><td>12/18/2018 21:46</td><td>10</td><td>10</td><td>100.0</td><td><span class=\"label success\">Success</span></td><td>SMS</td><td><a data-id=\"134717\" class=\"btn\" title=\"Go\">View</a></td></tr>"b1 = BS(data, "html.parser")td_of_interest = b1.find_all("td")tr_that_contain_our_td = [x.parent for x in b1.find_all("td", string="ABCD")]ids_dict = defaultdict(list)# iterate over matched tr's to get their datesfor tr in tr_that_contain_our_td:&nbsp; &nbsp; extracted_id = tr.find("a")['data-id']&nbsp; &nbsp; for td in tr.find_all("td"):&nbsp; &nbsp; &nbsp; &nbsp; try:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if len(td.contents) > 0:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; actual_date = du_parser.parse(td.contents[0])&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ids_dict[extracted_id].append(actual_date)&nbsp; &nbsp; &nbsp; &nbsp; except ValueError:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; pass&nbsp; #nothing to do hereids_dict = {k: max(v) for k, v in ids_dict.items()}print(ids_dict)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python