问题描述
作为家庭作业项目的一部分,我正在处理 imdb.com 个页面。
对于一项任务,我需要发出 320 个 get-requests 以便稍后将它们转换为 beautifulsoup 对象。
我正在尝试以异步方式做到这一点,到目前为止我得到了这个:
def get_tasks(session,url_links):
tasks = []
num = 1 # debugging purposes
for url in url_links:
tasks.append(session.get(url,headers={'Accept-Language': 'en','X_FORWARDED_FOR': '2.21.184.0'},ssl=False))
time.sleep(1) # avoid 503 status_code
print(f"Number of responses get_tasks: {num}") # debugging purposes
num += 1 # debugging purposes
return tasks
# Getting response.texts
results = []
async def get_response_texts(url_links):
async with aiohttp.ClientSession() as session:
tasks = get_tasks(session,url_links)
responses = await asyncio.gather(*tasks)
t1 = time.perf_counter()
num = 1
for response in responses:
results.append(await response.text())
print(f"{num} responses processed") # debugging purposes
num += 1
t2 = time.perf_counter()
print(f'Asynchronous execution: Finished in {t2 - t1} seconds\n')
if __name__ == '__main__':
links = [a list of urls to films as strings]
asyncio.run(get_response_texts(links))
print(len(results))
问题来了:当我处理 100 个请求时,事情似乎没问题,但是当我处理 300 个请求时,我得到 asyncio.exceptions.TimeoutError
。
为什么会这样,我怎样才能避免这种情况并异步发出 320 个请求?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)