python3使用代理ip訪問指定網站__python

來源:互聯網
上載者:User

首先要找一個可以提供代理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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.