如何使用Python将以下代码的输出“span.text [pos + 2:]”转换为整数:
我尝试过int(span.text [pos + 2:]),但不起作用
from bs4 import BeautifulSoup
import urllib2
url = "https://maps.google.com.au/maps?saddr=A6&daddr=A6&hl=en&ll=-33.877613,151.039867&spn=0.081236,0.083599&sll=-33.869204,151.034546&sspn=0.081244,0.083599&geocode=FYSu-v0d2KMACQ%3BFbp0-_0dJKoACQ&mra=ls&t=m&z=14&layer=t"
content = urllib2.urlopen(url).read()
soup = BeautifulSoup(content)
div = soup.find('div', {'class':'altroute-rcol altroute-aux'}) #get the div where it's located
span = div.find('span')
pos = span.text.find(': ')
print 'Current Listeners:', span.text[pos+2:]
更新:显示一些变量的内容可能会有所帮助:
span.text == u'In current traffic: 8 mins'
span.text[pos+2:] == u'8 mins'
答案 0 :(得分:1)
在这种特殊情况下,以下内容将起作用。我不确定它有多脆弱。
int(span.text[pos+2:].split(" ")[0])
如下:
In [31]: span.text
Out[31]: u'In current traffic: 8 mins'
In [32]: span.text[pos+2:]
Out[32]: u'8 mins'
In [33]: span.text[pos+2:].split(' ')
Out[33]: [u'8', u'mins']
In [34]: span.text[pos+2:].split(' ')[0]
Out[34]: u'8'
In [35]: int(span.text[pos+2:].split(' ')[0])
Out[35]: 8
答案 1 :(得分:-1)
也许你可以试试:
int(span.text[pos+2:])