如何 reset/clear aiohttp 会话
How to reset/clear aiohttp session
我已经用 aiohttp and back-connect proxies (the IP changes on each request). The biggest issue with working with back-connect proxies, is sometimes you do not get a good proxy. Regardless though, I still need the request to go through for that specific URL no matter what. I created an example that requests http://ip4.me 进行了 10,000 次测试并检索了 IP 地址。一开始一切正常,但最终,它开始出现错误:
local variable 'ip' referenced before assignment
这个错误的原因是因为我在请求后得到的页面是一些重定向页面,它将您带到某个随机站点。这是 HTML(真的没关系,但我想我会描绘全貌)。
<html><head><meta content="2;url=http://ip4.me/?" http-equiv="refresh"/></head><body><iframe frameborder="0" id="f" style="width:1;height:1"></iframe><script>document.getElementById("f").src="http://168.126.130.229/tm/?a=CR&b=WIN&c=300017519516&d=32&e=2205&f=aXA0Lm1l&g=1520816781875&h="+Date.now()+"&y=0&z=0&x=1&w=2017-11-29&in=2205_00002350&id=20180312"</script></body></html>
我猜我得到这个页面是因为它是对这么多请求的某种防御或类似的东西?现在通常当我收到请求错误(错误的代理,加载时间过长等)时,我会继续尝试,直到得到良好的响应(90% 的时间都有效,而这个例子是 运行).就像我之前提到的,在最后(可能还剩下 10 个请求要提出)。它将不断收到我在上面发布的 HTML 和我在上面发布的错误。这种情况会不断发生。
我认为发生这种情况的唯一原因是正在使用同一个会话,所以该网站以某种方式知道这一点,并一直给我这个重定向页面(不允许它跳出 While 循环) .当然,也可能有其他原因。如果有人对为什么会这样有任何见解?或者甚至是一种更好的重试请求的方法(如果我得到一个错误的代理等),我们将不胜感激!下面是我的完整工作示例,如果您有任何问题,请告诉我。感谢您的宝贵时间!
import asyncio
import aiohttp
from bs4 import BeautifulSoup
from datetime import datetime
from aiohttp.resolver import AsyncResolver
class Proxy:
def __init__(self, headers, proxy):
self.headers = headers
self.proxy = proxy
async def build(self, dataset):
tasks = []
resolver = AsyncResolver(nameservers=["8.8.8.8", "8.8.4.4"])
connector = aiohttp.TCPConnector(limit=1500, limit_per_host=0, resolver=resolver, use_dns_cache=False)
async with aiohttp.ClientSession(connector=connector) as session:
for data in range(0,dataset):
task = asyncio.ensure_future(self.fetch(session, data))
tasks.append(task)
r = await asyncio.gather(*tasks)
return r
async def fetch(self, session, data):
while True:
try:
async with session.get('http://ip4.me', headers=self.headers, proxy=self.proxy, timeout=60, ssl=False, allow_redirects=False) as resp:
assert resp.status == 200
r = await resp.read()
soup = BeautifulSoup(r, 'lxml')
for font in soup.find_all('font'):
ip = font.text
print (data, ip)
return ip
except Exception as e:
print (e)
if __name__ == '__main__':
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36'}
proxy = 'XXX.XX.X.XXX:XXXXX'
proxy = "http://{}".format(proxy)
dataset = 10000
px = Proxy(headers, proxy)
startTime = datetime.now()
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
future = asyncio.ensure_future(px.build(dataset))
ip = loop.run_until_complete(future)
loop.close()
print (datetime.now() - startTime)
抓取是个大话题。
在你的表达中,我想象你在每个请求中使用不同的代理。但是在您的代码中,我认为您对每个请求都使用相同的代理和相同的 headers。
因此在这种情况下,无论您如何更改 python 中的 session 代码,服务器都非常容易识别您的身份。因为你的IP从来没有变过。够了。当服务器认为你应该被禁止时,它会禁止你的IP,然后你将被完全阻止,不管你怎么尝试。
一些网站提供专业的服务来解决爬取禁止。他们在一段时间内针对每个不同的请求使用不同的代理。他们使用随机生成的用户代理来装扮成不同的浏览器。他们还使用庞大的数据库来决定相关策略。
所以这并不容易。如果你想获取一点数据,你可以放慢速度。
使用新的session
....
resolver = AsyncResolver(nameservers=["8.8.8.8", "8.8.4.4"])
connector = aiohttp.TCPConnector(limit=1500, limit_per_host=0, resolver=resolver, use_dns_cache=False, force_close=True)
sessions = []
for data in range(0,dataset):
session = aiohttp.ClientSession(connector=connector)
task = asyncio.ensure_future(self.fetch(session, data))
tasks.append(task)
sessions.append(session)
r = await asyncio.gather(*tasks)
[session.close() for session in sessions]
return r
....
force_close=True
可能没用,因为您对每个请求使用不同的 session。
我已经用 aiohttp and back-connect proxies (the IP changes on each request). The biggest issue with working with back-connect proxies, is sometimes you do not get a good proxy. Regardless though, I still need the request to go through for that specific URL no matter what. I created an example that requests http://ip4.me 进行了 10,000 次测试并检索了 IP 地址。一开始一切正常,但最终,它开始出现错误:
local variable 'ip' referenced before assignment
这个错误的原因是因为我在请求后得到的页面是一些重定向页面,它将您带到某个随机站点。这是 HTML(真的没关系,但我想我会描绘全貌)。
<html><head><meta content="2;url=http://ip4.me/?" http-equiv="refresh"/></head><body><iframe frameborder="0" id="f" style="width:1;height:1"></iframe><script>document.getElementById("f").src="http://168.126.130.229/tm/?a=CR&b=WIN&c=300017519516&d=32&e=2205&f=aXA0Lm1l&g=1520816781875&h="+Date.now()+"&y=0&z=0&x=1&w=2017-11-29&in=2205_00002350&id=20180312"</script></body></html>
我猜我得到这个页面是因为它是对这么多请求的某种防御或类似的东西?现在通常当我收到请求错误(错误的代理,加载时间过长等)时,我会继续尝试,直到得到良好的响应(90% 的时间都有效,而这个例子是 运行).就像我之前提到的,在最后(可能还剩下 10 个请求要提出)。它将不断收到我在上面发布的 HTML 和我在上面发布的错误。这种情况会不断发生。
我认为发生这种情况的唯一原因是正在使用同一个会话,所以该网站以某种方式知道这一点,并一直给我这个重定向页面(不允许它跳出 While 循环) .当然,也可能有其他原因。如果有人对为什么会这样有任何见解?或者甚至是一种更好的重试请求的方法(如果我得到一个错误的代理等),我们将不胜感激!下面是我的完整工作示例,如果您有任何问题,请告诉我。感谢您的宝贵时间!
import asyncio
import aiohttp
from bs4 import BeautifulSoup
from datetime import datetime
from aiohttp.resolver import AsyncResolver
class Proxy:
def __init__(self, headers, proxy):
self.headers = headers
self.proxy = proxy
async def build(self, dataset):
tasks = []
resolver = AsyncResolver(nameservers=["8.8.8.8", "8.8.4.4"])
connector = aiohttp.TCPConnector(limit=1500, limit_per_host=0, resolver=resolver, use_dns_cache=False)
async with aiohttp.ClientSession(connector=connector) as session:
for data in range(0,dataset):
task = asyncio.ensure_future(self.fetch(session, data))
tasks.append(task)
r = await asyncio.gather(*tasks)
return r
async def fetch(self, session, data):
while True:
try:
async with session.get('http://ip4.me', headers=self.headers, proxy=self.proxy, timeout=60, ssl=False, allow_redirects=False) as resp:
assert resp.status == 200
r = await resp.read()
soup = BeautifulSoup(r, 'lxml')
for font in soup.find_all('font'):
ip = font.text
print (data, ip)
return ip
except Exception as e:
print (e)
if __name__ == '__main__':
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36'}
proxy = 'XXX.XX.X.XXX:XXXXX'
proxy = "http://{}".format(proxy)
dataset = 10000
px = Proxy(headers, proxy)
startTime = datetime.now()
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
future = asyncio.ensure_future(px.build(dataset))
ip = loop.run_until_complete(future)
loop.close()
print (datetime.now() - startTime)
抓取是个大话题。
在你的表达中,我想象你在每个请求中使用不同的代理。但是在您的代码中,我认为您对每个请求都使用相同的代理和相同的 headers。
因此在这种情况下,无论您如何更改 python 中的 session 代码,服务器都非常容易识别您的身份。因为你的IP从来没有变过。够了。当服务器认为你应该被禁止时,它会禁止你的IP,然后你将被完全阻止,不管你怎么尝试。
一些网站提供专业的服务来解决爬取禁止。他们在一段时间内针对每个不同的请求使用不同的代理。他们使用随机生成的用户代理来装扮成不同的浏览器。他们还使用庞大的数据库来决定相关策略。
所以这并不容易。如果你想获取一点数据,你可以放慢速度。
使用新的session
....
resolver = AsyncResolver(nameservers=["8.8.8.8", "8.8.4.4"])
connector = aiohttp.TCPConnector(limit=1500, limit_per_host=0, resolver=resolver, use_dns_cache=False, force_close=True)
sessions = []
for data in range(0,dataset):
session = aiohttp.ClientSession(connector=connector)
task = asyncio.ensure_future(self.fetch(session, data))
tasks.append(task)
sessions.append(session)
r = await asyncio.gather(*tasks)
[session.close() for session in sessions]
return r
....
force_close=True
可能没用,因为您对每个请求使用不同的 session。