Trimming the outputs in python

Adi*_*mar 3 python beautifulsoup python-3.x

I made something which gets the time from https://time.is/ and shows the time. I used BeautifulSoup and urllib.request.

But I want to trim the output. I'm getting this as output and I want to remove the code part.

<div id="twd">07:29:26</div>
Run Code Online (Sandbox Code Playgroud)

Program File:

import urllib.request
from bs4 import BeautifulSoup

url = 'https://time.is/'
hdr = { 'User-Agent' : 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)' }

req = urllib.request.Request(url, headers=hdr)
res = urllib.request.urlopen(req)
soup = BeautifulSoup(res, 'html.parser')
string = soup.find(id='twd')
print(string)
Run Code Online (Sandbox Code Playgroud)

How can I get just the text?

Ste*_*uch 6

您可以使用以下命令从dom元素获取文本.text

string.text
Run Code Online (Sandbox Code Playgroud)

测试代码:

import urllib.request
from bs4 import BeautifulSoup

url = 'https://time.is/'
hdr = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)'}

req = urllib.request.Request(url, headers=hdr)
res = urllib.request.urlopen(req)
soup = BeautifulSoup(res, 'html.parser')
string = soup.find(id='twd')
print(string.text)
Run Code Online (Sandbox Code Playgroud)

结果:

07:06:11PM
Run Code Online (Sandbox Code Playgroud)