【发布时间】:2014-04-22 00:03:13
【问题描述】:
我有一个 .txt 文件(名为 test_1.txt),其格式如下:
https://maps.googleapis.com/maps/api/directions/xml?origin=Bethesda,MD&destination=Washington,DC&sensor=false&mode=walking
https://maps.googleapis.com/maps/api/directions/xml?origin=Miami,FL&destination=Mobile,AL&sensor=false&mode=walking
https://maps.googleapis.com/maps/api/directions/xml?origin=Chicago,IL&destination=Scranton,PA&sensor=false&mode=walking
https://maps.googleapis.com/maps/api/directions/xml?origin=Baltimore,MD&destination=Charlotte,NC&sensor=false&mode=walking
如果您转到上述链接之一,您将看到 XML 格式的输出。使用下面编写的代码,我设法让它迭代到第二个方向请求(迈阿密到移动),它打印看似随机的数据,这不是我想要的。我也能够让这个工作,当只使用 .txt 但直接从代码中一次访问一个 URL 时,准确地打印我需要的数据。是否有任何理由只转到第二个 URL 并打印错误信息? Python代码如下:
import urllib2
from bs4 import BeautifulSoup
with open('test_1.txt', 'r') as f:
f.readline()
mapcalc = f.readline()
response = urllib2.urlopen(mapcalc)
soup = BeautifulSoup(response)
for leg in soup.select('route > leg'):
duration = leg.duration.text.strip()
distance = leg.distance.text.strip()
start = leg.start_address.text.strip()
end = leg.end_address.text.strip()
print duration
print distance
print start
print end
编辑:
这是 Shell 中 Python 代码的输出:
56
1 min
77
253 ft
Miami, FL, USA
Mobile, AL, USA
【问题讨论】:
-
是的,原因是您调用了两次
readline(),并使用第二个返回值创建了BeautifulSoup对象。如果不是要打开的第二个 URL,您期望什么? -
那么我将如何将其更改为只调用一次呢?我还是个新手,所以请原谅我的经验不足!
-
在
with语句之后的第一行中,您第一次调用f.readline()。它返回文件的第一行,但不以任何方式处理。删除该行,您将看到第一个 URL 的输出。 -
那我如何让它遍历所有的 URl?一个链接将不胜感激。
标签: python python-2.7 beautifulsoup urllib2