Python模拟浏览器实现网页访问
生活随笔
收集整理的這篇文章主要介紹了
Python模拟浏览器实现网页访问
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
模擬瀏覽器請(qǐng)求數(shù)據(jù):
import socket# 創(chuàng)建TCP鏈接 tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # DNS 解析和鏈接HTTP服務(wù)器 tcp_socket.connect(("www.qq.com", 80))# 編寫請(qǐng)求頭, 發(fā)送HTTP請(qǐng)求報(bào)文 # 請(qǐng)求行 request_line = "GET / HTTP/1.1\r\n" # 請(qǐng)求頭,設(shè)置請(qǐng)求域名 request_header = "www.qq.com\r\n" request_data = request_line + request_header + "\r\n"# 發(fā)送請(qǐng)求 tcp_socket.send(request_data.encode("utf-8")) # 接收響應(yīng)報(bào)文,指定長(zhǎng)度 response_data = tcp_socket.recv(4096) # 對(duì)響應(yīng)報(bào)文進(jìn)行解析 --切割 response_str_data = response_data.decode("utf-8") print(response_data) # "\r\n\r\n" 之后的數(shù)據(jù)就是響應(yīng)體數(shù)據(jù) index = response_str_data.find("\r\n\r\n") # 切割出的數(shù)據(jù)就是文件數(shù)據(jù) html_data = response_str_data[index+4:] # 在當(dāng)前路徑下新建文件存儲(chǔ)響應(yīng)數(shù)據(jù) with open("index.html", "wb") as file:file.write(html_data.encode()) # 關(guān)閉套接字 tcp_socket.close()轉(zhuǎn)載于:https://blog.51cto.com/10412806/2095303
總結(jié)
以上是生活随笔為你收集整理的Python模拟浏览器实现网页访问的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql版本选择最终建议
- 下一篇: Python3 图片(jpg、bmp、p