python使用代理后成功访问网站但测试ip依然是主机ip
使用urllib
from urllib import request
from bs4 import BeautifulSoup
url = 'https://www.ip.cn/'
req = request.Request(url)
req.add_header('User-Agent', 'Mozilla/6.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/8.0 Mobile/10A5376e Safari/8536.25')
proxy = {'HTTPS': '110.191.132.218:8081'}
proxy_handler = request.ProxyHandler(proxy)
opener = request.build_opener(proxy_handler)
print(proxy_handler.proxies)
with opener.open(req) as f:
data = f.read()
soup = BeautifulSoup(data, 'html.parser')
result = soup.find_all(attrs={'id': 'result'})[0]
print(result.text)
使用requests
import requests
from bs4 import BeautifulSoup
url='https://www.ip.cn/'
resp=requests.get(url,proxies={'HTTPS': 'http://110.191.132.218:8081'})
soup = BeautifulSoup(resp.content, 'html.parser')
result = soup.find_all(attrs={'id': 'result'})[0]
print(result.text)
两个输出一样
使用SSR软件设置代理
之前从西刺代理获取了上百个代理随机访问廖雪峰python教程,然后还是被封了本机ip,当时就觉得很奇怪,麻烦帮忙看一下代码有没有问题或者其他问题
又想了想,可能是因为从西刺爬的免费高匿代理失效了或者透明了导致本机ip暴露,就重新爬取,通过ping 百度发现筛选下来的都是http的无效,就重新筛选https的,从第一页只爬到几条,但是测试发现代理ip成功了
看来代码没有问题,是代理的问题,而且未暴露的只有https的代理