Python爬蟲設定代理IP的方法(爬蟲技巧),python爬蟲

來源:互聯網
上載者:User

Python爬蟲設定代理IP的方法(爬蟲技巧),python爬蟲

在學習Python爬蟲的時候,經常會遇見所要爬取的網站採取了反爬取技術,高強度、高效率地爬取網頁資訊常常會給網站伺服器帶來巨大壓力,所以同一個IP反覆爬取同一個網頁,就很可能被封,這裡講述一個爬蟲技巧,設定代理IP。

(一)配置環境

  • 安裝requests庫
  • 安裝bs4庫
  • 安裝lxml庫

(二)代碼展示

# IP地址取自國內髙匿代理IP網站: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)函數get_ip_list(url, headers)傳入url和headers,最後返回一個IP列表,列表的元素類似42.84.226.65:8888格式,這個列表包括國內髙匿代理IP網站首頁所有IP地址和連接埠。 

函數get_random_ip(ip_list)傳入第一個函數得到的列表,返回一個隨機的proxies,這個proxies可以傳入到requests的get方法中,這樣就可以做到每次運行都使用不同的IP訪問被爬取的網站,有效地避免了真實IP被封的風險。proxies的格式是一個字典:{‘http': ‘http://42.84.226.65:8888‘}

(三)代理IP的使用

運行上面的代碼會得到一個隨機的proxies,把它直接傳入requests的get方法中即可。

web_data = requests.get(url, headers=headers, proxies=proxies)

總結

以上所述是小編給大家介紹的Python爬蟲設定代理IP的方法(爬蟲技巧),希望對大家有所協助,如果大家有任何疑問歡迎給我留言,小編會及時回複大家的!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.