urllib2.URLError:<urlopen error =“”unknown =“”url =“”type:=“”c =“”> </urlopen>

时间:2013-01-11 15:45:20

标签: python python-2.7 beautifulsoup urllib2 microformats

我使用以下代码从网页http://ajaxian.com中删除XFN内容 但我正在收集以下错误:

    Traceback (most recent call last):  File      "C:\Users\Somnath\workspace\us.chakra.social.web.microformat\src\microformats_xfn_scrape.py", line 40, in <module>
page = urllib2.urlopen(URL)
  File "C:\Python27\lib\urllib2.py", line 126, in urlopen
return _opener.open(url, data, timeout)
  File "C:\Python27\lib\urllib2.py", line 394, in open
response = self._open(req, data)
  File "C:\Python27\lib\urllib2.py", line 417, in _open
'unknown_open', req)
  File "C:\Python27\lib\urllib2.py", line 372, in _call_chain
result = func(*args)
  File "C:\Python27\lib\urllib2.py", line 1232, in unknown_open
raise URLError('unknown url type: %s' % type)
urllib2.URLError: <urlopen error unknown url type: c>

我的代码如下:

'''
Created on Jan 11, 2013

@author: Somnath
'''
# Scraping XFN content from a web page
# -*-coding: utf-8 -*-

import sys
import urllib2
import HTMLParser
from BeautifulSoup import BeautifulSoup

# Try http://ajaxian.com
URL = sys.argv[0]

XFN_TAGS = set([
            'colleague',
            'sweetheart',
            'parent',
            'co-resident',
            'co-worker',
            'muse',
            'neighbor',
            'sibling',
            'kin',
            'child',
            'date',
            'spouse',
            'me',
            'acquaintance',
            'met',
            'crush',
            'contact',
            'friend',
            ])


#try:
page = urllib2.urlopen(URL)
#except urllib2.URLError:
#    print 'Failed to fetch ' + item

#try:
soup = BeautifulSoup(page)
#except HTMLParser.HTMLParseError:
#    print 'Failed to parse ' + item

anchorTags = soup.findAll('a')

for a in anchorTags:
    if a.has_key('rel'):
        if len(set(a['rel'].split()) & XFN_TAGS) > 0:
            tags = a['rel'].split()
            print a.contents[0], a['href'], tags

我在Eclipse下运行PyDev并使用Run As - &gt; Python运行并使用参数“http://ajaxian.com/”设置运行时配置。任何人都可以建议我哪里出错了吗?

还有一件事:我在代码中评论了两个try块,因为它给出了一个错误未定义的变量:item。如果我想重新包含try-except块,我应该在try块外面给出变量的空白定义吗?我该怎样摆脱这个问题?

1 个答案:

答案 0 :(得分:4)

正如您所建议的,sys.argv[0]打印脚本的路径,这是因为您调用脚本

python microformats_xfn‌​_scrape.py <some_argument>

这里sys.argv的索引0是脚本的名称而不是参数。

您需要做的是使用<url>参数调用脚本,例如:

python microformats_xfn‌​_scrape.py http://www.ajaxian.com/

并在您的脚本中将sys.argv[0]更改为sys.argv[1],因为url参数索引为1。

相关问题