我们可以使用urllib或urllib2或请求或机械化在python中重新加载页面/ url?

我们可以使用urllib或urllib2或请求或机械化在python中重新加载页面/ url?

问题描述:

我试图打开一个页面/链接并捕获它中的内容。 它有时会给我所需的内容,有时会引发错误。 我看到,如果我刷新页面几次 - 我收到内容。我们可以使用urllib或urllib2或请求或机械化在python中重新加载页面/ url?

所以,我想重新加载页面并抓住它。

这里是我的伪代码:

attempts = 0 
while attempts: 
    try: 
     open_page = urllib2.Request(www.xyz.com) 
     # Or I think we can also do urllib2.urlopen(www.xyz.com) 
     break 
    except: 
     # here I want to refresh/reload the page 
     attempts += 1 


我的问题是:
1.如何重装使用的urllib或urllib2的或请求或机械化的页面?
2.我们可以循环试试这种方式吗?

谢谢!

import requests 
from requests.adapters import HTTPAdapter 
from requests.packages.urllib3.util.retry import Retry 

attempts = 10 

retries = Retry(total=attempts, 
      backoff_factor=0.1, 
      status_forcelist=[ 500, 502, 503, 504 ]) 

sess = requests.Session() 
sess.mount('http://', HTTPAdapter(max_retries=retries)) 
sess.mount('https://', HTTPAdapter(max_retries=retries)) 
sess.get('http://www.google.co.nz/') 

如果你做while attempts当尝试等于0你永远不会开始循环。我会做反了,初始化attempts等于您想要重新加载的数量:

attempts = 10 
while attempts: 
    try: 
     open_page = urllib2.Request('www.xyz.com') 
    except: 
     attempts -= 1 
    else: 
     attempts = False 

后续的功能提出了一些例外或HTTP响应状态代码后刷新不是200

def retrieve(url): 
    while 1: 
     try: 
      response = requests.get(url) 
      if response.ok: 
       return response 
      else: 
       print(response.status) 
       time.sleep(3) 
       continue 
     except: 
      print(traceback.format_exc()) 
      time.sleep(3) 
      continue