(비동기 크롤러) 요청 및 aiohttp에서 프록시 IP 사용

(비동기 크롤러) 요청 및 aiohttp에서 프록시 IP 사용


크롤러가 잘 크롤링하려면 IP 프록시가 필수입니다. . 이제 웹 사이트는 기본적으로 크롤링 방지 조치를 취하고 있습니다. 액세스 속도가 약간 빠르면 IP가 차단 된 것을 발견하고 그렇지 않으면 확인을 위해 제출합니다. 다음은 프록시 IP 사용에 대해 설명하기 위해 일반적으로 사용되는 두 가지 모듈입니다. 할 말이 많지 않고 시작하십시오.

여기에 사진 설명 삽입

요청 에 프록시 IP 사용 : 요청 에 프록시 IP 를 사용하려면 프록시 매개 변수 만 추가하면됩니다. 프록시의 매개 변수 값은 딕셔너리, 키는 프록시 프로토콜 (http / https), 값은 ip 및 포트 번호이며 구체적인 형식은 다음과 같습니다.

try:
    response = requests.get('https://httpbin.org/ip', headers=headers, 
    	proxies={
    
    'https':'https://221.122.91.74:9401'}, timeout=6)
    print('success')
    # 检测代理IP是否使用成功
    # 第一种方式,返回发送请求的IP地址,使用时要在 get() 添加 stream = True
    # print(response.raw._connection.sock.getpeername()[0])
    # 第二种方式,直接返回测试网站的响应数据的内容
    print(response.text)
except Exception as e:
    print('error',e)

여기에 사진 설명 삽입
참고 : peoxies의 키 값 (http / https)은 URL과 일치해야합니다. 그렇지 않으면 로컬 IP를 사용하여 직접 액세스됩니다.

aiohttp에서 프록시 IP 사용 :
요청 모듈이 비동기를 지원하지 않기 때문에 aiohttp가 강제로 사용되며 많은 구덩이가 삭제됩니다.
사용법은 요청과 비슷합니다. 또한 get () 메소드에 매개 변수를 추가하지만 현재 매개 변수 이름은 프록시이고 매개 변수 값은 문자열이며 문자열의 프록시 프로토콜은 http 만 지원합니다. https로 작성되면 오류가보고됩니다..
여기 내 오류 수정 프로세스에 대한 기록이 있습니다. .
우선 온라인 사용에 따라 다음 코드를 먼저 시도해 보았습니다.

async def func():
    async with aiohttp.ClientSession() as session:
        try:
            async with session.get("https://httpbin.org/ip", headers=headers, 
            			proxy='http://183.220.145.3:80', timeout=6) as response:
                page_text = await response.text()
                print('success')
                print(page_text)
        except Exception as e:
            print(e)
            print('error')

if __name__=='__main__':
    asyncio.run(func())

여기에 사진 설명 삽입
수정 후 다시 오세요

async def func():
    con = aiohttp.TCPConnector(verify_ssl=False)
    async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(verify_ssl=False)) as session:
        try:
            async with session.get("https://httpbin.org/ip", headers=headers, 
            proxy='http://183.220.145.3:80', timeout=6) as response:
                # print(response.raw._connection.sock.getpeername()[0])
                page_text = await response.text()
                print(page_text)
                print('success')
        except Exception as e:
            print(e)
            print('error')

여기에 사진 설명 삽입
여기에 사진 설명 삽입
문제를 해결하는 대신 추가 경고가 있지만 다행히 변경하는 것이 좋습니다. 어 ~ 너무 게으 르기 때문에 최종판으로 넘어 가자. .

# 修改事件循环的策略,不能放在协程函数内部,这条语句要先执行
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
async def func():
	# 添加trust_env=True
    async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(ssl=False), trust_env=True) as session:
        try:
            async with session.get("https://httpbin.org/ip", headers=headers,
             proxy='http://183.220.145.3:80', timeout=10) as response:
                page_text = await response.text()
                print(page_text)
                print('success')
        except Exception as e:
            print(e)
            print('error')

여기에 사진 설명 삽입
오류 수정 프로세스는 약간 길지만 다행히 사용 방법을 알고 있습니다.

마지막에는 아름다운 그림 사유 나라 ~
여기에 사진 설명 삽입

추천

출처blog.csdn.net/qq_43965708/article/details/109622238