這篇文章主要內(nèi)容是對(duì)西刺網(wǎng)站上的免費(fèi)IP進(jìn)行爬取和驗(yàn)證掂碱,來(lái)保證對(duì)其他項(xiàng)目的需求躏敢。
- 目標(biāo)網(wǎng)址:http://www.xicidaili.com/nn/
通過(guò)查看元素商佛,ip地址喉钢、端口、類型都可以在一個(gè)tr里找到良姆。
目標(biāo)網(wǎng)站
- 爬取ip肠虽,端口,協(xié)議三個(gè)信息玛追,并放入隊(duì)列税课,等待檢查加入數(shù)據(jù)庫(kù)闲延。
def get_info(self, q):
page = 1
while True:
url = 'http://www.xicidaili.com/nn/%d' % (page)
req = requests.get(url, headers=self.header)
soup = BeautifulSoup(req.text, 'lxml')
trs = soup.find('table', id='ip_list').find_all('tr')
for tr in trs[1:]:
ip = tr.contents[3].text
port = tr.contents[5].text
procotol = tr.contents[11].text
q.put((ip, port, procotol.lower()))
page += 1
- 從隊(duì)列中取出信息,并用它訪問(wèn)一個(gè)網(wǎng)站韩玩,如果成功把它存到數(shù)據(jù)庫(kù)中為可用IP垒玲。
def check(self, q, lock):
while True:
data = q.get()
try:
req = requests.get('http://www.baidu.com',
proxies={'%s' % (data[2]): '%s://%s:%s'
% (data[2], data[0], data[1])},
timeout=2, headers=self.header,
cookies=self.cookie)
if req.status_code == 200:
print(data)
tools.i_ip(data)
else:
print('not200', data)
except Exception as e:
print(e, 'erro', data)
pass
GitHub開源地址:https://github.com/matianhe/crawler