使用python转换为int

使用python转换为int,python,int,Python,Int,如何使用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&a

如何使用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'
也许你可以试试:

int(span.text[pos+2:])

在这种特殊情况下,以下操作将起作用。但我不确定它有多脆弱

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

当它不起作用时,它会说什么?
int(something)
会将某个东西转换为int,如果失败则会引发一个ValueError。
span.text[pos+2:]
在您的情况下会导致
8分钟
。您想将该字符串中的
8
作为int吗?那么当您尝试
int(…)
时发生了什么?我必须说,“不起作用”在寻求任何技术问题的帮助时都不是一个有用的短语。除非我们知道发生了什么,否则我们无法提供帮助,而“不起作用”通常甚至不会告诉我们发生了什么。@Ossama:我编辑了你的文章,以显示span.text的可能内容。如果这是错误的,请编辑我的更改。