我正在尝试提取NextBus数据,特别是在这里看到的实时总线GPS:http://webservices.nextbus.com/service/publicXMLFeed?command=vehicleLocations&a=sf-muni&r=N&t=0
在其中,有些标签看起来像这样:
<vehicle id="1534" routeTag="N" dirTag="N__OB1" lat="37.76931" lon="-122.43249"
secsSinceReport="99" predictable="true" heading="265" speedKmHr="37"/>
我正在学习python并且已经走过去成功地根据属性拉取标签。但我正在努力寻找除了id之外的任何属性。
这样可行:
soup.findAll("vehicle", {"id":"1521"})[1]
但是这会返回一个空集
soup.findAll("vehicle", {"routeTag":"N"})
有什么理由?
另外,正如我所提到的,我对Python很新,所以如果你有一个最喜欢的抓取教程,请随时发表评论!
答案 0 :(得分:0)
要使其正常运行,您应该将xml
传递给BeautifulSoup
构造函数:
from urllib2 import urlopen
from bs4 import BeautifulSoup
url = 'http://webservices.nextbus.com/service/publicXMLFeed?command=vehicleLocations&a=sf-muni&r=N&t=0'
soup = BeautifulSoup(urlopen(url), "xml")
print soup.find_all("vehicle", {"routeTag":"N"})
打印:
[
<vehicle heading="-4" id="1431" lat="37.72223" lon="-122.44694" predictable="false" routeTag="N" secsSinceReport="65" speedKmHr="0"/>,
...
]
或者,感谢@ Martijn的评论,请用小写字母进行搜索:
print soup.find_all("vehicle", {"routetag": "N"})
另请注意,您应该使用BeautifulSoup4和find_all()方法 - 不会维护第3个BeautifulSoup
版本。