【发布时间】: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