Python中使用socket发送HTTP请求数据接收不完整问题解决方法

WBOY
Release: 2016-06-10 15:18:01
Original
1521 people have browsed it

由于工作的需求,需要用python做一个类似网络爬虫的采集器。虽然Python的urllib模块提供更加方便简洁操作,但是涉及到一些底层的需求,如手动设定User-Agent,Referer等,所以选择了直接用socket进行设计。当然,这样的话,需要对HTTP协议比较熟悉,HTTP协议这里就不做讲解了。整个python的代码如下:

#!/usr/bin env python
import socket
host="www.baidu.com"
se=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
se.connect((host,80))
se.send("GET / HTTP/1.1\n")
se.send("Accept:text/html,application/xhtml+xml,*/*;q=0.8\n")
#se.send("Accept-Encoding:gzip,deflate,sdch\n")
se.send("Accept-Language:zh-CN,zh;q=0.8,en;q=0.6\n")
se.send("Cache-Control:max-age=0\n")
se.send("Connection:keep-alive\n")
se.send("Host:"+host+"\r\n")
se.send("Referer:http://www.baidu.com/\n")
se.send("user-agent: Googlebot\n\n")
print se.recv(1024)

Copy after login

代码运行正常,但是发现一个比较重要的问题,运行结果只返回了HTTP的头部信息,网页的内容则没有被返回。网上查找了很多资料,一无所获,经过一夜的思考,突然想到了一个问题,有可能我请求的资源非常大,一个网络的IP包的大小,它是受很多因素制约的,最典型的便是MTU(最大传输单元),那么会不会我请求的数据被分割了,HTTP的头部信息只是一部分,其它数据还在传输或者缓冲区呢?于是做了这样一个遍历:

while True:
  buf = se.recv(1024)
  if not len(buf):
    break
  print buf

Copy after login

这样发现所有请求的数据均被返回了,看来要想做好网络编程,深入理解TCP/IP协议是非常必要的。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!