【问题标题】:Can we replace urlopen in this code with requests library?我们可以用 requests 库替换这段代码中的 urlopen 吗?
【发布时间】:2017-07-09 22:57:24
【问题描述】:

我们可以用 python 2.7 中的 requests 库替换这个例子中并发请求的 urlopen 库吗?

import concurrent.futures
import urllib.request

URLS = ['http://www.foxnews.com/',
        'http://www.cnn.com/',
        'http://europe.wsj.com/',
        'http://www.bbc.co.uk/',
        'http://some-made-up-domain.com/']

# Retrieve a single page and report the URL and contents
def load_url(url, timeout):
    with urllib.request.urlopen(url, timeout=timeout) as conn:
        return conn.read()

# We can use a with statement to ensure threads are cleaned up promptly
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
    # Start the load operations and mark each future with its URL
    future_to_url = {executor.submit(load_url, url, 60): url for url in URLS}
    for future in concurrent.futures.as_completed(future_to_url):
        url = future_to_url[future]
        try:
            data = future.result()
        except Exception as exc:
            print('%r generated an exception: %s' % (url, exc))
        else:
            print('%r page is %d bytes' % (url, len(data)))

谢谢!

【问题讨论】:

    标签: concurrency python-requests concurrent.futures


    【解决方案1】:

    是的,你可以。

    您的代码似乎做了一个简单的 HTTP get 超时,所以请求的等价物是:

    import requests
    
    def load_url(url, timeout):
        r = requests.get(url, timeout=timeout)
        return r.content
    

    【讨论】:

      猜你喜欢
      • 2012-05-18
      • 1970-01-01
      • 2011-10-21
      • 2013-08-18
      • 1970-01-01
      • 1970-01-01
      • 2017-06-24
      • 1970-01-01
      • 2018-04-30
      相关资源
      最近更新 更多