在python中修剪输出

时间:2019-05-13 02:03:49

标签: python python-3.x beautifulsoup

我做了一些事情,从https://time.is/获取时间并显示了时间。我使用BeautifulSoup和urllib.request。

但是我想修剪输出。我将其作为输出,并且要删除代码部分。

<div id="twd">07:29:26</div>

程序文件:

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)

我如何只获取文字?

1 个答案:

答案 0 :(得分:6)

您可以使用.text从dom元素中获取文本,例如:

string.text

测试代码:

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)

结果:

07:06:11PM