>  기사  >  백엔드 개발  >  Python 크롤러가 프록시 IP를 확보하고 가용성을 확인하는 예

Python 크롤러가 프록시 IP를 확보하고 가용성을 확인하는 예

不言
不言원래의
2018-05-07 12:00:341752검색

이 글은 주로 Python 크롤러가 프록시 IP를 잡아서 가용성을 확인하는 예를 소개합니다. 확실한 참고 가치가 있습니다. 이제 도움이 필요한 친구들이 참고할 수 있습니다.

크롤러를 자주 작성하다 보면 필연적으로 IP가 발생하게 됩니다. 대상 웹사이트가 차단되면 확실히 IP 주소 하나만으로는 충분하지 않습니다. 알뜰한 프로그래머로서 돈을 들이지 않고 할 수 있다면 직접 찾으러 가십시오. 이번에는 서쪽에서 IP 주소를 얻는 것에 대해 썼습니다. Spur 프록시이지만 이 웹사이트는 크롤링 방지 기능도 갖추고 있습니다. ! !

대처 방법은 지연 시간을 늘려보시면 될 것 같습니다. 너무 자주 크롤링을 해서 IP가 차단된 것 같습니다.

그러나 모든 길은 로마로 통하며 나무에 매달릴 수는 없습니다.

말도 안 돼요. 코드를 시작해 보겠습니다.

#!/usr/bin/env python
# -*- coding:utf8 -*-
import urllib2
import time
from bs4 import BeautifulSoup
import sys
reload(sys)
sys.setdefaultencoding( "utf-8" )
req_header = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
 'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
 #'Accept-Language': 'en-US,en;q=0.8,zh-Hans-CN;q=0.5,zh-Hans;q=0.3',
 'Accept-Charset':'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
 'Accept-Encoding':'en-us',
 'Connection':'keep-alive',
 'Referer':'http://www.baidu.com/'
 }
req_timeout = 5
testUrl = "http://www.baidu.com/"
testStr = "wahaha"
file1 = open('proxy.txt' , 'w')
# url = ""
# req = urllib2.Request(url,None,req_header)
# jsondatas = urllib2.urlopen(req,None,req_timeout).read()
cookies = urllib2.HTTPCookieProcessor()
checked_num = 0
grasp_num = 0
for page in range(1, 160):
 req = urllib2.Request('http://www.xici.net.co/nn/' + str(page), None, req_header)
 html_doc = urllib2.urlopen(req, None, req_timeout).read()
 # html_doc = urllib2.urlopen('http://www.xici.net.co/nn/' + str(page)).read()
 soup = BeautifulSoup(html_doc)
 trs = soup.find('table', id='ip_list').find_all('tr')
 for tr in trs[1:]:
  tds = tr.find_all('td')
  ip = tds[1].text.strip()
  port = tds[2].text.strip()
  protocol = tds[5].text.strip()
  if protocol == 'HTTP' or protocol == 'HTTPS':
   #of.write('%s=%s:%s\n' % (protocol, ip, port))
   print '%s=%s:%s' % (protocol, ip, port)
   grasp_num +=1
   proxyHandler = urllib2.ProxyHandler({"http": r'http://%s:%s' % (ip, port)})
   opener = urllib2.build_opener(cookies, proxyHandler)
   opener.addheaders = [('User-Agent',
         'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36')]
   t1 = time.time()
   try:
    req = opener.open(testUrl, timeout=req_timeout)
    result = req.read()
    timeused = time.time() - t1
    pos = result.find(testStr)
    if pos > 1:
     file1.write(protocol+"\t"+ip+"\t"+port+"\n")
     checked_num+=1
     print checked_num, grasp_num
    else:
     continue
   except Exception,e:
    continue
file1.close()
print checked_num,grasp_num

개인적으로는 코드가 너무 복잡하다고 느껴지지 않아서 기본적으로 다들 이해하실 거라 생각합니다. 궁금한 점이 있으면 비판하고 수정해 주세요. 그래서 우리는 함께 발전할 수 있습니다!

관련 권장 사항:

Python으로 프록시 IP를 수집하고 사용 가능한지 확인하고 정기적으로 업데이트하는 방법

위 내용은 Python 크롤러가 프록시 IP를 확보하고 가용성을 확인하는 예의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.