2017-03-02 27 views
0
import urllib2 

    def download(url,user_agent = 'wswp',num_retries=2): 
     print 'downloading:',url 
     headers = {'User-Agent': 'Mozilla/5.0'} 
     request = urllib2.Request(url,headers=headers) 
     try: 
      html = urllib2.urlopen(request).read() 
     except urllib2.URLError as e: 
      print "download error:" 
      html = None 
      if num_retries>0: 
       if hasattr(e,'code') and 500<=e.code<600: 
        print "e.code = ",e.code 
        return download(url,num_retries-1) 
     return html 
    print download("http://www.huaru.cc/mobile/product/xsim.html") 

结果工作\ Python27 \ python.exe E:/ py2_7 /未命名/ secondClass_Agent下载: http://www.huaru.cc/mobile/product/xsim.html蟒的urllib2无法在某些现场

过程,退出代码完成0

+2

在我的机器上工作。我修好了缩进之后。 –

+0

也适用于我的机器。检查你的缩进。 – sangheestyle

+0

嗨,你的意思是你可以下载本网站的所有代码?你能粘贴你的结果吗?谢谢。 –

回答

0

在Python中,缩进是关键。

import urllib2 


def download(url,user_agent = 'wswp',num_retries=2): 
    print('downloading:', url) 
    headers = {'User-Agent': 'Mozilla/5.0'} 
    request = urllib2.Request(url, headers=headers) 
    try: 
     html = urllib2.urlopen(request).read() 
    except urllib2.URLError as e: 
     print("download error: {}".format(e)) 
     html = None 
     if num_retries > 0: 
      if hasattr(e, 'code') and 500 <= e.code < 600: 
       print("e.code = ", e.code) 
       return download(url, num_retries-1) 
    return html 

print download("http://www.huaru.cc/mobile/product/xsim.html") 

它表明类似如下:

('downloading:', 'http://www.huaru.cc/mobile/product/xsim.html') 
download error: HTTP Error 404: Not Found 
None 

这是因为网页是返回404

这是对Python的2.7.10测试和3.6

检查PEP8: https://www.python.org/dev/peps/pep-0008/#id17

+0

我知道缩进,但我不知道如何纠正它在这个web.I为此抱歉。我仍然遇到您粘贴的代码错误。你可以粘贴你的结果与运行这个代码。谢谢很多。 –

+0

@ Zhang.h不用担心。你不需要说抱歉。相反,再试一次。我修改了我的代码,告诉你什么是错误。当然,该网址会返回HTTP 404,这意味着找不到。我发现该网站显示404。 – sangheestyle