简体   繁体   English

使用python转换为int

[英]convert to int using python

How can I convert the output "span.text[pos+2:]" of the code below to an integer using Python: 如何使用Python将以下代码的输出“ span.text [pos + 2:]”转换为整数:

I have tried int(span.text[pos+2:]), but does not work 我已经尝试过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:]

Update: It may be helpful to show the contents of a few variables: 更新:显示一些变量的内容可能会有所帮助:

span.text == u'In current traffic: 8 mins'
span.text[pos+2:] == u'8 mins'

In this particular case, the following will work. 在这种特殊情况下,以下将起作用。 I'm not sure how fragile it is though. 我不确定它有多脆弱。

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

As follows: 如下:

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(span.text[pos+2:])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM