如何使用python和BeautifulSoup打印每行的时间戳/上次更新时间(来自HTML)?

c9qzyr3d  于 2022-10-22  发布在  Python
关注(0)|答案(1)|浏览(202)

如何使用python和BeautifulSoup打印每行的时间戳/上次更新时间(来自HTML)?
1.我可以添加打印内容吗
a) 日期/时间-显示执行python代码的时间
b) HTML的上次更新时间:
HTML结构:

  1. td x 1 including
  2. two tables
  3. each table have few "tr"
  4. and within "tr" have few "td" data inside

HTML格式:

  1. <td>
  2. <table width="100%" border="4" cellspacing="0" bordercolor="white" align="center">
  3. <tbody>
  4. <tr>
  5. <td colspan="2" class="verd_black11">Last Updated: 18/08/2014 10:19</td>
  6. </tr>
  7. <tr>
  8. <td colspan="3" class="verd_black11">All data delayed at least 15 minutes</td>
  9. </tr>
  10. </tbody>
  11. </table>
  12. <table width="100%" border="4" cellspacing="0" bordercolor="white" align="center">
  13. <tbody id="tbody">
  14. <tr id="tr0" class="tableHdrB1" align="center">
  15. <td align="centre">C Aug-14 - 15000</td>
  16. <td align="right"> - </td>
  17. <td align="right">5</td>
  18. <td align="right">9,904</td>
  19. </tr>
  20. </tbody>
  21. </table>
  22. </td>

代码:

  1. import urllib2
  2. from bs4 import BeautifulSoup
  3. contenturl = "HTML:"
  4. soup = BeautifulSoup(urllib2.urlopen(contenturl).read())
  5. table = soup.find('tbody', attrs={'id': 'tbody'})
  6. rows = table.findAll('tr')
  7. for tr in rows:
  8. cols = tr.findAll('td')
  9. for td in cols:
  10. t = td.find(text=True)
  11. if t:
  12. text = t + ';'
  13. print text,
  14. print

上述代码的输出

  1. C Aug-14 - 15000 ; - ; 5 ; 9,904

预期产出:

  1. C Aug-14 - 15000 ; - ; 5 ; 9,904 ; 18/08/2014 ; 13:48:00 ; 18/08/2014 ; 10:19
  2. (execute python code) (last updated time)
cnwbcb6i

cnwbcb6i1#

要获取代码执行的时间:

  1. import datetime from datetime
  2. code_executes = datetime.now()

然后从code_executes元组中选择所需的片段,并将其格式化为字符串,以便稍后插入下面的print语句
要获得“最后更新”位,您需要读取顶部的表,因为它没有您指定的id属性。如果html只有2个表,您可能可以删除漂亮汤的id规范,您将获得两个表。
要获取时间,请使用str.startswih(“Last Updated:”)并获取之后的内容(字符串切片将起作用)
最后,在打印时,将您的两次粘贴到线条上

相关问题