python - 如何批量处理 get 请求中的 URL 列表?

标签 python python-3.x concurrency python-multithreading

我有一个需要传递到 API 的 ID 列表。

成功地将 ID 放入 URL 字符串中,并且我有一个包含约 300k 个 url(约 300K ID)的列表

我想获取每个 api 回调的文本部分并在列表中。

我可以通过获取每个 ID 并使用 for 循环将其传递到 URL 中来实现此目的,如下所示,而无需迭代列表:

L = [1,2,3]

    for i in L:
        #print (row)
        url = 'url&Id={}'.format(i)
        xml_data1 = requests.get(url).text
        lst.append(xml_data1)
        time.sleep(1)
        print(xml_data1)

我一直在尝试使用 concurrent.futuresurllib.request 以及库一次发送多个请求,但我不断收到错误:

username=xxxx&password=xxxx&Id=1' generated an exception: 'HTTPResponse' object has no attribute 'readall'

使用此代码:

lst = [url.com,url2.com]

URLS = lst

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

# 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() 
            # do json processing here
        except Exception as exc:
            print('%r generated an exception: %s' % (url, exc))
        else:
            print('%r page is %d bytes' % (url, len(data)))

如何调整我的 for 循环或上面的代码以同时进行多个 API 调用?

我问这个问题是因为我的连接不断被 for 循环重置,而且我不知道如何从 ID 或 url 方面继续我离开的地方。

使用python3.6

编辑:

我从这里应用了代码Python requests with multithreading

其中 lst 是 url 列表。

class Test:
    def __init__(self):
        self.urls = lst

    def exception(self, request, exception):
        print ("Problem: {}: {}".format(request.url, exception))

    def async(self):
        results = grequests.map((grequests.get(u) for u in self.urls), exception_handler=self.exception, size=5)
        print (results)

test = Test()
test.async()

代码似乎工作正常,没有给出错误消息,但是如何从代码中将response.text附加到列表中?

最佳答案

按照此处建议的请求: Python requests with multithreading

它不会直接适应您已有的代码,您可能必须使用不同的库重新编写,但它听起来更适合您的需求。

我们的进一步沟通。请参阅下面的代码,其中说明了要更改的内容。

import grequests
lst = ['https://www.google.com', 'https://www.google.cz']
class Test:
    def __init__(self):
        self.urls = lst

    def exception(self, request, exception):
        print ("Problem: {}: {}".format(request.url, exception))

    def async(self):
        return grequests.map((grequests.get(u) for u in self.urls), exception_handler=self.exception, size=5)


    def collate_responses(self, results):
        return [x.text for x in results]
test = Test()
#here we collect the results returned by the async function
results = test.async()
response_text = test.collate_responses(results)

关于python - 如何批量处理 get 请求中的 URL 列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51953712/

相关文章:

python - 如何重命名文件夹中的图像

python - 过滤标签与 taggit 中其他模型的关系

python - Django 或 python 与 Mercurial 一起使用时如何处理 pyc 文件?

python-3.x - 信号量 Python 是如何工作的

python - 如何在 Pandas 中用数字对字符串进行排序?

python discord.py 在加入公会时向邀请者发送 DM

c++ - 2 个不同的 task_group 实例不并行运行任务

python - 从 Tensorflow 过滤 "empty"值

java - 并发模式失败,而 Full GC

go - 如何使用 channel 广播消息