首先要找一個可以提供代理ip的網站,然後爬下網站上的ip地址和連接埠號碼。最後用爬取出來的ip做代理訪問指定網站。
關鍵地方我用紅色箭頭標註出來了。分頁解析代碼如下
def getProxyIp(): proxy = [] for i in range(1, 3): print(i) header = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) ' 'AppleWebKit/537.36 (KHTML, like Gecko) ' 'Ubuntu Chromium/44.0.2403.89 ' 'Chrome/44.0.2403.89 ' 'Safari/537.36'} req = urllib.request.Request(url='http://www.xicidaili.com/nt/{0}'.format(i), headers=header) r = urllib.request.urlopen(req) soup = BeautifulSoup(r,'html.parser',from_encoding='utf-8') table = soup.find('table', attrs={'id': 'ip_list'}) tr = table.find_all('tr')[1:] #解析得到代理ip的地址,連接埠,和類型 for item in tr: tds = item.find_all('td') temp_dict = {} kind = "{0}:{1}".format(tds[1].get_text().lower(), tds[2].get_text()) proxy.append(kind) return proxy
head是模仿瀏覽器請求。將最後解析出來ip和連接埠號碼的結果放在proxy裡面。然後開始用代理訪問指定網站。
proxy_handler = urllib.request.ProxyHandler({'http': proxy_dict}) opener = urllib.request.build_opener(proxy_handler) urllib.request.install_opener(opener) req = urllib.request.Request(url="http://blog.csdn.net/u013692888/article/details/52714103", headers=header) urllib.request.urlopen(req)源碼地址https://github.com/Ahuanghaifeng/python3-ip