在學(xué)習(xí)Python爬蟲的時(shí)候,經(jīng)常會(huì)遇見所要爬取的網(wǎng)站采取了反爬取技術(shù),高強(qiáng)度、高效率地爬取網(wǎng)頁信息常常會(huì)給網(wǎng)站服務(wù)器帶來巨大壓力,所以同一個(gè)IP反復(fù)爬取同一個(gè)網(wǎng)頁,就很可能被封,這里講述一個(gè)爬蟲技巧,設(shè)置代理IP。
(一)配置環(huán)境
安裝requests庫 安裝bs4庫 安裝lxml庫(二)代碼展示
# IP地址取自國內(nèi)髙匿代理IP網(wǎng)站:http://www.xicidaili.com/nn/# 僅僅爬取首頁IP地址就足夠一般使用from bs4 import BeautifulSoupimport requestsimport randomdef get_ip_list(url, headers): web_data = requests.get(url, headers=headers) soup = BeautifulSoup(web_data.text, 'lxml') ips = soup.find_all('tr') ip_list = [] for i in range(1, len(ips)): ip_info = ips[i] tds = ip_info.find_all('td') ip_list.append(tds[1].text + ':' + tds[2].text) return ip_listdef get_random_ip(ip_list): proxy_list = [] for ip in ip_list: proxy_list.append('http://' + ip) proxy_ip = random.choice(proxy_list) proxies = {'http': proxy_ip} return proxiesif __name__ == '__main__': url = 'http://www.xicidaili.com/nn/' headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36' } ip_list = get_ip_list(url, headers=headers) proxies = get_random_ip(ip_list) print(proxies)函數(shù)get_ip_list(url, headers)傳入url和headers,最后返回一個(gè)IP列表,列表的元素類似42.84.226.65:8888格式,這個(gè)列表包括國內(nèi)髙匿代理IP網(wǎng)站首頁所有IP地址和端口。 函數(shù)get_random_ip(ip_list)傳入第一個(gè)函數(shù)得到的列表,返回一個(gè)隨機(jī)的proxies,這個(gè)proxies可以傳入到requests的get方法中,這樣就可以做到每次運(yùn)行都使用不同的IP訪問被爬取的網(wǎng)站,有效地避免了真實(shí)IP被封的風(fēng)險(xiǎn)。proxies的格式是一個(gè)字典:{‘http': ‘http://42.84.226.65:8888‘}。
(三)代理IP的使用
運(yùn)行上面的代碼會(huì)得到一個(gè)隨機(jī)的proxies,把它直接傳入requests的get方法中即可。
web_data = requests.get(url, headers=headers, proxies=proxies)
總結(jié)
以上所述是小編給大家介紹的Python爬蟲設(shè)置代理IP的方法(爬蟲技巧),希望對(duì)大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會(huì)及時(shí)回復(fù)大家的!
新聞熱點(diǎn)
疑難解答
圖片精選