【问题标题】:IndexError: list index out of range [Python 3.x Web scraping]IndexError:列表索引超出范围 [Python 3.x Web 抓取]
【发布时间】:2017-04-20 23:24:23
【问题描述】:

我正在尝试通过搜索 twitter、tweet url 来使用 csv 中的 URL 获取地理位置。输入文件有超过 100K 行和一堆列。

我正在使用带有所有更新版本的 python 3.x anaconda,我收到以下错误:

Traceback (most recent call last):
  File "__main__.py", line 21, in <module>
    location = get_location(userid)
  File "C:path\twitter_location.py", line 22, in get_location
    location = html.select('.ProfileHeaderCard-locationText')[0].text.strip()
IndexError: list index out of range

下面的代码:

#!/usr/env/bin python
import urllib.request
import urllib3
from bs4 import BeautifulSoup

def get_location(userid):
    '''
    Get location as string ('Paris', 'New york', ..) by scraping twitter profils page.
    Returns None if location can not be scrapped
    '''

    page_url = 'http://twitter.com/{0}'.format(userid)

    try:
        page = urllib.request.urlopen(page_url)
    except urllib.request.HTTPError:
        print ('ERROR: user {} not found'.format(userid))
        return None

    content = page.read()
    html = BeautifulSoup(content)
    location = html.select('.ProfileHeaderCard-locationText')[0].text.strip()

    if location.strip() == '':
        return None
    return location.strip()

我正在寻找一种快速修复方法,以便我可以执行超过 100k 行的整个输入文件。

编辑:我 如下面的答案所述,在包含try 块后,输出已停止获取地理位置。

在包含 try 块之前,在某些计数 list out of range 错误之后。

包含try 块后,错误消失了,坐标也消失了。我得到了所有none 值。

这是DropBox 链接,其中包含输入、输出之前和之后以及整个代码包。

编辑:II

整个代码和输入都在 Dropbox 中

感谢您在解决问题方面的帮助。提前致谢。

【问题讨论】:

  • 我的猜测是某些内容中没有'.ProfileHea ...',因此html select给出了一个没有索引0的空列表
  • @EzerK 谢谢你的建议,在那种情况下,我怎么能忽略这样一行并继续下一步呢?我正在尝试使用('.ProfileHeaderCard-locationText')[-1] 并执行。让我看看在这种情况下它是如何工作的。

标签: python web-scraping beautifulsoup urllib3 indexoutofrangeexception


【解决方案1】:

嗯,你有一个对 HTTPErrors 的异常处理,但是如果没有.ProfileHeaderCard-locationText,就没有处理。这大概就是问题所在。现在轮到你 可以导入/实现

import logging
logging.warning('Watch out!')  # will print a message to the console
logging.info('I told you so')  # will not print anything
logging.exception()

您可以在所有程序中使用它(并且应该!)。 就像你添加了一个try,除了`try的块:

try:
    page = urllib.request.urlopen(page_url)
except urllib.request.HTTPError:
    print('ERROR: user {} not found'.format(userid))
    return None

你也可以这样做

try:
    location = html.select('.ProfileHeaderCard-locationText')[0].text.strip()
except Exception:
    print("Error,Hey dud couldn't find Profile...")

主要问题可能是 Google 限制了他们的 API 的使用。更方便的方法是使用Google-Maps-Python-API 点击查看详情 用法示例:

from geolocation.google_maps import GoogleMaps

address = "New York City Wall Street 12"

google_maps = GoogleMaps(api_key='your_google_maps_key') 

location = google_maps.search(location=address) # sends search to Google Maps.

print(location.all()) # returns all locations.

my_location = location.first() # returns only first location.

print(my_location.city)
print(my_location.route)
print(my_location.street_number)
print(my_location.postal_code)

编辑:

    if location.strip() == '':
        return None
return location.strip()

我想你的意思是:

if location.strip()==None:
    return None
else:
    return location.strip()

【讨论】:

  • 非常感谢您的建议但是在这段代码中,我应该使用logging 的哪个部分?但是需要一种方法来跳过输入中的特定内容并继续解析下一行?不是吗?
  • 我已经添加了代码,你可以使用 try: except 块在你的代码中你期望错误的任何地方(出于任何原因),现在只使用 except Exception 是一种非常草率的做事方式,但我这样做了,它完成了工作。 *对于这种情况,您可以使用除了 IndexError: print("There's no .profileHeaderCard, move on...")
  • 非常感谢..让我尝试添加并执行,并会通知您。
  • 当然,请确保您提供反馈并解释您的问题/编辑您的问题,添加代码以方便您和我们。提示:如果您认为自己不知道自己在寻找什么,请索要解释该主题的视频/文档。
  • 我包含了try: 块,但这给了我缩进错误try: ^ TabError: inconsistent use of tabs and spaces in indentation
【解决方案2】:

虽然按照故障保险丝的回答中的建议处理“索引超出范围”异常很重要,但这只会解决症状。

问题的根源是在一定数量的请求之后,twitter 会阻止您的 IP 并停止发送任何可用的内容。 (他们不喜欢这样的大量查询)。

可能的解决方案:

  1. 慢一点。这将延迟被 Twitter 阻止。你需要走得很慢,你根本不会被阻塞。虽然这对于 10 万条记录可能是不可能的,但如果您有时间等待结果,这将是一个简单的解决方法。

  2. 使用旋转代理。使用其中的许多。 ...或者结合一些代理,速度稍微慢一些。

【讨论】:

  • 非常感谢..你能帮我在代码中编写延迟块吗..这对我来说将是巨大的帮助..可能就像一次 100 个查询并暂停 n 延迟又是一些查询..直到最后..请尝试帮助代码..
  • 当然,如果你想走慢速路线,我会在你的循环中放入一个 time.sleep(wait_seconds),它会遍历所有用户 ID,然后尝试不同的 wait_seconds 值,从 wait_seconds=2 开始并根据您的测试结果上下调整。
  • 请你帮忙编辑代码。我已经用 Dropbox 链接把所有的输入、输出和代码放在了问题中。这对我有很大的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-16
  • 1970-01-01
  • 2023-04-11
  • 2018-03-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多