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

Logo

欢迎加入 MCP 技术社区!与志同道合者携手前行,一同解锁 MCP 技术的无限可能!

更多推荐