"""
使用ip代理进行网站访问,(反封禁ip手段)
"""
from urllib import request
import chardet
class BaiDu(object):
def baidu(self):
url = "https://www.baidu.com/"
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:67.0) Gecko/20100101 Firefox/67.0"
}
# 1.使用代理ip,构建字典
proxy = {"http": "182.34.32.54:39219"}
# 2.构建代处理器
proxyHandler = request.ProxyHandler(proxy)
# 3. 构建一个url打开器
opener = request.build_opener(proxyHandler)
# 4.安装url打开器
request.install_opener(opener)
# 声明请求对象的时候 注入请求头 修改User-Agent(身份)
req = request.Request(url, headers=headers)
# 获取二进制流 网页源代码
bytesHtml = request.urlopen(req).read()
# 判断网页编码格式,返回一个字典
htmlEncode = chardet.detect(bytesHtml)
# 进行解码,返回一个字符串类型的文本
html = bytesHtml.decode(htmlEncode["encoding"])
print(html)
if __name__ == '__main__':
bd = BaiDu()
bd.baidu()