如何批量获取请求中的 URL 列表?
How to batch list of URLs in get request?
我有一个 ID 列表需要传递到 API。
成功地,我将 ID 变成了 url 字符串,并且我有一个包含 ~300k urls(~300K IDs)
的列表
我想获取每个 api 回调的文本部分并放入列表中。
我可以通过获取每个 ID 并将其传递到 URL 使用 for 循环来做到这一点,而无需遍历列表:
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.futures
和 urllib.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
编辑:
我应用了这里的代码
其中 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 附加到列表中?
此处建议的 grequests:
它不会直接改编您已有的代码,您可能不得不使用不同的库重新编写,但它听起来更适合您的需要。
我们的交流更进一步。请参阅下面的代码,其中说明了要更改的内容。
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)
我有一个 ID 列表需要传递到 API。
成功地,我将 ID 变成了 url 字符串,并且我有一个包含 ~300k urls(~300K IDs)
的列表我想获取每个 api 回调的文本部分并放入列表中。
我可以通过获取每个 ID 并将其传递到 URL 使用 for 循环来做到这一点,而无需遍历列表:
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.futures
和 urllib.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
编辑:
我应用了这里的代码
其中 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 附加到列表中?
此处建议的 grequests:
它不会直接改编您已有的代码,您可能不得不使用不同的库重新编写,但它听起来更适合您的需要。
我们的交流更进一步。请参阅下面的代码,其中说明了要更改的内容。
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)