0

如何使用 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'
4

2 回答 2

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
于 2013-10-31T20:17:02.870 回答
-1

也许你可以试试:

int(span.text[pos+2:])
于 2013-10-31T20:11:29.773 回答