標籤:

跟黃哥學Python爬蟲抓取代理IP。

為了防止被反爬蟲策略禁止訪問,有的時候需要用到代理IP,代理IP可以到一些提供

代理IP的網站上爬取,也可以自己掃描。(想想這些提供代理IP的網站是怎麼得到這些代理IP的,是通過掃描得來的)。

下面的代碼用到requests和BeautifulSoup,到一個網站上採集IP,為了初學者學習方便,只取前面10頁的內容,

請大家修改代碼。

# coding:utf-8nnimport requestsnfrom bs4 import BeautifulSoupnnnclass SpiderProxy(object):n """黃哥Python培訓 黃哥所寫 Python版本為2.7以上"""n headers = {n "Host": "www.xicidaili.com",n "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:47.0) Gecko/20100101 Firefox/47.0",n "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",n "Accept-Language": "en-US,en;q=0.5",n "Accept-Encoding": "gzip, deflate",n "Referer": "http://www.xicidaili.com/wt/1",n }nn def __init__(self, session_url):n self.req = requests.session()n self.req.get(session_url)nn def get_pagesource(self, url):n html = self.req.get(url, headers=self.headers)n return html.contentnn def get_all_proxy(self, url, n):n data = []n for i in range(1, n):n html = self.get_pagesource(url + str(i))n soup = BeautifulSoup(html, "lxml")nn table = soup.find(table, id="ip_list")n for row in table.findAll("tr"):n cells = row.findAll("td")n tmp = []n for item in cells:nn tmp.append(item.find(text=True))n data.append(tmp[1:3])n return datannsession_url = http://www.xicidaili.com/wt/1nurl = http://www.xicidaili.com/wt/np = SpiderProxy(session_url)nproxy_ip = p.get_all_proxy(url, 10)nfor item in proxy_ip:n if item:n print itemn

建議: 為了保持代理IP可用,需要創建一個代理池,定期檢測可用的代理,無效的代理及時刪除。可以用redis實現。

推薦閱讀:

TAG:Python |