因此,我一直在尝试使用aiohttp进行web抓取,并且遇到了这样的问题:每当我使用代理时,session.get中的代码都不会运行。我在互联网上到处找遍了,却找不到解决办法。
import asyncio
import time
import aiohttp
from aiohttp.client import ClientSession
import random
failed = 0
success = 0
proxypool = []
with open("proxies.txt", "r") as jsonFile:
lines = jsonFile.readlines()
for i in lines:
x = i.split(":")
proxypool.append("http://"+x[2]+":"+x[3].rstrip()+"@"+x[0]+":"+x[1])
async def download_link(url:str,session:ClientSession):
global failed
global success
proxy = proxypool[random.randint(0, len(proxypool))]
print(proxy)
async with session.get(url, proxy=proxy) as response:
if response.status != 200:
failed +=1
else:
success +=1
result = await response.text()
print(result)
async def download_all(urls:list):
my_conn = aiohttp.TCPConnector(limit=1000)
async with aiohttp.ClientSession(connector=my_conn,trust_env=True) as session:
tasks = []
for url in urls:
task = asyncio.ensure_future(download_link(url=url,session=session))
tasks.append(task)
await asyncio.gather(*tasks,return_exceptions=True) # the await must be nest inside of the session
url_list = ["https://www.google.com"]*100
start = time.time()
asyncio.run(download_all(url_list))
end = time.time()
print(f'download {len(url_list)-failed} links in {end - start} seconds')
print(failed, success)
但问题是,代码在我的mac上运行得很好。但是,当我试图在windows上运行完全相同的代码时,它不会运行。如果没有代理,它也能正常工作,但是一旦我添加它们,它就不能工作了。
最后,您可以看到,我打印失败和成功。在我的mac上,它将输出0,100,而在我的windows计算机上,它将打印0,0 -这证明代码没有运行(而且,没有打印)
我使用的代理是付费代理,如果我使用requests.get()
,它们将正常工作。它们的格式是"http://user:pass@ip:port"
我也尝试过使用"http://ip:port“,然后使用BasicAuth来携带用户和密码,但这也不起作用。
我见过很多人都有这个问题,但是这个问题似乎从来没有得到解决。
如能提供任何帮助,将不胜感激:)
发布于 2022-07-08 08:06:25
因此,经过更多的测试和研究,我发现了这个问题,我需要添加ssl = False
因此,提出请求的正确方法是:
async with session.get(url, proxy=proxy, ssl = False) as response:
对我起作用了。
https://stackoverflow.com/questions/72898373
复制相似问题