国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python爬蟲設(shè)置代理IP的方法(爬蟲技巧)

2020-02-22 23:21:37
字體:
供稿:網(wǎng)友

在學(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ù)大家的!

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 女性| 滕州市| 武安市| 墨江| 车致| SHOW| 昌平区| 岐山县| 滦平县| 雷波县| 容城县| 丽江市| 红原县| 绍兴市| 府谷县| 宾阳县| 乐陵市| 惠来县| 宝清县| 安国市| 随州市| 青阳县| 呈贡县| 苗栗市| 西丰县| 木兰县| 金华市| 海城市| 双城市| 砀山县| 南开区| 蒙山县| 临江市| 红桥区| 蒙阴县| 宾阳县| 长岛县| 阳曲县| 和静县| 民丰县| 亚东县|