0
点赞
收藏
分享

微信扫一扫

https获取网页内容的两种方法

日月同辉9908 2022-03-22 阅读 41
网络安全

方法1

from urllib import parse

import urllib.request

import requests
from requests.packages import urllib3
urllib3.disable_warnings()#对警告信息进行屏蔽

response = requests.get('https://www.12306.cn/mormhweb/', verify=False)# verify=False 意思是对证书不做校验
#采用根证书校验的方法response = requests.get('http://www.12306.cn',cert=('path/server.crt','path/key'))
# print(resp.cookies)
#print("打印客户端连接记录",((response.cookies.get(textwrap)).text).encode(encoding="utf-8"))






html = response.headers
html = response.content# 此处是打印网页经回话秘钥解码后的内容

print(html)










print("打印客户端连接记录",response.cookies)
print(response.status_code)

#打印获取的XML文件
print(response.text)#打印从12306获取的html网页,指定路径,注意key不能加密
f = open("12306网页"+".html", "wb")#将结果写入到html 里
f.write(response.content)  # 将结果写到XML文件里
f.close()  # 切记一定要close

方法2

from urllib import parse

import urllib.request

# 1. 导入Python SSL处理模块

import ssl

# 2. 表示忽略未经核实的SSL证书认证

context = ssl._create_unverified_context()#抛去证书认证的关键步骤

url = 'https://www.12306.cn/mormhweb/'

#headers={'User-Agent':'Mozilla/5.0(WindowsNT10.0;Win64;x64) AppleWebKit/537.36(KHTML,likeGecko)Chrome/70.0.3538.110Safari/537.36'}
headers={'User-Agent':'Mozilla/5.0(WindowsNT10.0;Win64;x64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/70.0.3538.110Safari/537.36'}#欺骗服务器说我是用户浏览器非代码访问

# url 作为Request()方法的参数,构造并返回一个Request对象

request = urllib.request.Request(url, headers=headers)

# Request对象作为urlopen()方法的参数,发送给服务器并接收响应

# 3. 在urlopen()方法里 指明添加 context 参数

response = urllib.request.urlopen(request, context=context)       #该处表明不对证书做验证

html = response.read().decode('utf-8')

print(html)


#打印获取的XML文件
f = open("12306网页方法2"+".html", "wb")#将结果写入到html 里
f.write(html.encode(encoding="utf-8"))  # 将结果写到XML文件里
f.close()  # 切记一定要close

参考文章:

举报

相关推荐

0 条评论