胡萝卜酱最近在爬取知乎用户数据,然而爬取不了一会,IP就被封了,所以去爬取了西刺代理IP来使用。
这里爬取的是西刺国内高匿IP。我们需要的就是这一串数字。
进群:548377875 即可获取数十套PDF以及大量的学习教程哦!都是从零基础到项目实战的!
分析源码后,发现数据非常的明了,都是存在表格里面,一行一行的展示,因此,我们只需要把这些数据存下来即可。为了防止IP被封,我们通过设置获取网页睡眠时间和随机选取header的方法。同时,我们通过百度来验证这些IP是否可用,可用的话,就存起来。
1import requests
2import re
3import time
4import random
5from bs4 import BeautifulSoup
6import pandas as pd
7keys = [
8 'Mozilla/5.0 (Linux; Android 4.1.1; Nexus 7 Build/JRO03D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Safari/535.19',
9 'Mozilla/5.0 (Linux; U; Android 4.0.4; en-gb; GT-I9300 Build/IMM76D) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30',
10 'Mozilla/5.0 (Linux; U; Android 2.2; en-gb; GT-P1000 Build/FROYO) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1',
11 'Mozilla/5.0 (Windows NT 6.2; WOW64; rv:21.0) Gecko/20100101 Firefox/21.0',
12 'Mozilla/5.0 (Android; Mobile; rv:14.0) Gecko/14.0 Firefox/14.0',
13 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.94 Safari/537.36',
14 'Mozilla/5.0 (Linux; Android 4.0.4; Galaxy Nexus Build/IMM76B) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.133 Mobile Safari/535.19',
15 'Mozilla/5.0 (iPad; CPU OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3',
16 'Mozilla/5.0 (iPod; U; CPU like Mac OS X; en) AppleWebKit/420.1 (KHTML, like Gecko) Version/3.0 Mobile/3A101a Safari/419.3'
17]
18def get_ip_list(k):
19 ip_list = []
20 print("正在获取代理列表...")
21 for i in range(1,k+1):
22 try:
23 url = 'http://www.xicidaili.com/nn/' + str(i)
24 header = {'User-Agent': keys[random.randint(0, len(keys) - 1)]}
25 html = requests.get(url=url, headers=header).text
26 soup = BeautifulSoup(html, 'lxml')
27 ips = soup.find(id='ip_list').find_all('tr')
28 for j in range(1, len(ips)):
29 ip_info = ips[j]
30 tds = ip_info.find_all('td')
31 ip = tds[1].text + ':' + tds[2].text
32 # 用这个网页去验证,遇到不可用ip会抛异常
33 url = "https://www.baidu.com/"
34 try:
35 proxies = {'http': 'http://' + ip}
36 res = requests.get(url, headers=header, proxies=proxies).text
37 ip_list.append('http://' + ip)
38 except Exception as e:
39 print (e)
40 continue
41 print("第{}页代理列表抓取成功.".format(i))
42 time.sleep(5 + float(random.randint(1,100)) /20)
43 except Exception as e:
44 print('error:',e)
45 return ip_list
46ip_list = get_ip_list(20)
47
48pd.DataFrame(columns = ['ip'], data = ip_list).to_csv('ip_list.csv',encoding='utf-8',index = False)
49print('一共获得{}个IP地址'.format(len(ip_list)))
不足五十行的代码,我们就获取2000个可用IP,在以后需要爬取其他网页,就可以随时调取一个来使用。值得注意的是,这些IP可能会过期,建议验证后使用,若失效则从IP池里删除。
网友评论