【问题标题】:Iterate and make requests over a list of URLs asynchronously异步迭代 URL 列表并发出请求
【发布时间】:2020-12-28 04:55:53
【问题描述】:

前几天晚上我编写了一个脚本,该脚本使用不同的 URL 编号(范围从 0000 到 10000)向网站发出了 100000 次请求。我正在使用请求库,但它非常慢。这是我当前的脚本:

import requests

for num in range(9999):
    num = '{0:04}'.format(num)
    print(num)
    URL = "www.site.com/" + str(num)
    r = requests.get(url = URL)
    print(r.content)

我听说 aiohttp 允许异步请求,但考虑到我想要实现的目标,我不确定最简单的方法。有什么想法吗?

【问题讨论】:

  • 我提供的具有可配置池大小的并发线程解决方案:stackoverflow.com/questions/65365783/… 如果这对您的情况来说还不够 - 请在此处告诉我。
  • 谢谢你,虽然我不完全确定如何适应我的情况?
  • 您可以尝试运行 bash 脚本。多处理更容易实现。
  • 我该怎么做?
  • 一篇适合您的案例的好文章是在 requestsgevent stackoverflow.com/a/38280387/5973377 的基础上使用 grequests

标签: python asynchronous url python-requests aiohttp


【解决方案1】:

我提供的可配置池大小的并发线程解决方案:How do connections recycle in a multiprocess pool serving requests from a single requests.Session object in python?

谢谢你,虽然我不完全确定如何适应我的情况?

from concurrent.futures.thread import ThreadPoolExecutor
from functools import partial

from requests import Session, Response
from requests.adapters import HTTPAdapter


list_of_urls = [("www.site.com/" + "{0:04}".format(num)) for num in range(9999)] # one row difference with the solution from link above


def thread_pool_execute(iterables, method, pool_size=30) -> list:
    """Multiprocess requests, returns list of responses."""
    session = Session()
    session.mount('https://', HTTPAdapter(pool_maxsize=pool_size))
    session.mount('http://', HTTPAdapter(pool_maxsize=pool_size))
    worker = partial(method, session)
    with ThreadPoolExecutor(pool_size) as pool:
        results = pool.map(worker, iterables)
    session.close()
    return list(results)

def simple_request(session, url) -> Response:
    return session.get(url)

response_list = thread_pool_execute(list_of_urls, simple_request)

【讨论】:

  • 谢谢!我刚刚尝试运行它并得到“NameError: name 'partial' is not defined” - 这是我需要定义的方法吗?
  • 泰。修复了帖子。添加了from functools import partial
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-02
  • 2011-01-08
  • 1970-01-01
相关资源
最近更新 更多