【问题标题】:Iterating through list of URLs in Python - bs4遍历 Python 中的 URL 列表 - bs4
【发布时间】: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


【解决方案1】:

这是一个link,它可以更清楚地说明您在打开文件和阅读行等时可能遇到的行为(与 Lev Levitsky 的评论有关)。

一种方式:

import httplib2
from bs4 import BeautifulSoup

http = httplib2.Http()
with open('test_1.txt', 'r') as f:
    for mapcalc in f:
        status, response = http.request(mapcalc)
        for leg in BeautifulSoup(response):
            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

f.close()

我是这种事情的新手,但我得到了上面的代码来处理以下输出:

4877
1 hour 21 mins
6582
4.1 mi
Bethesda, MD, USA
Washington, DC, USA
56
1 min
77
253 ft
Miami, FL, USA
Mobile, AL, USA
190
3 mins
269
0.2 mi
Chicago, IL, USA
Scranton, PA, USA
12
1 min
15
49 ft
Baltimore, MD, USA
Charlotte, NC, USA

【讨论】:

  • 哪个工作得很好而且很快,但我不能让它始终打印总距离和持续时间?你能想到什么理由吗?
  • 您是否使用上述提供的数据看到不一致的结果?或者,除了您提供的内容之外,您是否看到来自多个来源的不同结果?即您的原始网址。
  • 嘿,我看到 python 脚本提取了错误的 XML 标签(增量而不是每次都相同),但现在我正在使用 LXML xpath 方法并且它工作得很好!
猜你喜欢
  • 2021-11-19
  • 2016-08-27
  • 2011-09-14
  • 2022-11-22
  • 1970-01-01
  • 1970-01-01
  • 2013-02-18
  • 1970-01-01
相关资源
最近更新 更多