0
我尝试使用Twisted Agent来实现HTTP客户端并下载完整网页的特定URL,最后测量该特定网站的加载时间页。不幸的是,我所提供的代码并没有遵循HTML标签中的内部URL,因此,从浏览器上的其他网站下载一些内容后需要10秒完成加载的网页将不到一秒钟完全加载在我的代码中,这表明我的代码不正确!即使我使用BrowserLikeRedirectAgent和RedirectAgent,结果也是一样的。任何意见表示赞赏。扭曲的HTTP客户端下载整个页面并测量下载时间
def init_http(url):
userAgent = 'Twisted/%s (httpclient.py)' % (version.short(),)
agent = BrowserLikeRedirectAgent(Agent(reactor))
def response_time_calculator(test,t1):
end_time = time.time()
response_time = end_time - t1
print ("Got the Whole page in: ", response_time)
start_time = time.time()
d = agent.request(
b'GET', str(url), Headers({'user-agent': [userAgent]}))
def cbResponse(response):
if response.length is not UNKNOWN_LENGTH:
print('The response body will consist of', response.length, 'bytes.')
else:
print('The response body length is unknown.')
d = readBody(response)
d.addCallback(response_time_calculator, start_time)
return d
d.addCallback(cbResponse)
感谢time.clock,我只需要加载标签,所以他们的地址不能反馈给Twisted代理,有关它的任何解决方法?我宁愿不在我的代码中实现一个新的库,所以使用scrapy并不是我想要的,我寻找一种解决方案来单独处理Twisted和Python。 – DeFoG
如果你不想使用scrapy,你需要做一些事情来解析html,找到img标签,解释它们的来源,并发出新的'Agent.request'调用。 Twisted中没有任何内容会为你做这个链接。 Twisted中也没有真正的html解析器。在stdlib中有一个很老的,不太好的,但我真的推荐你使用'html5lib',它实现了html5规范,并且这是目前解析html的唯一理智方式。 –