Python http下载页sou

2024-04-19 19:09:47 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
3条回答

关于httplib(低级)和urllib(高级)的文档应该可以帮助您开始。选择一个更适合你的。

您可以使用urllib2模块。

import urllib2
url = "http://somewhere.com"
page = urllib2.urlopen(url)
data = page.read()
print data

更多示例请参见文档

Using urllib2 to download a page.

谷歌将阻止此请求,因为它将尝试阻止所有机器人。向请求添加用户代理。

import urllib2
user_agent = 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_4; en-US) AppleWebKit/534.3 (KHTML, like Gecko) Chrome/6.0.472.63 Safari/534.3'
headers = { 'User-Agent' : user_agent }
req = urllib2.Request('http://www.google.com', None, headers)
response = urllib2.urlopen(req)
page = response.read()
response.close() # its always safe to close an open connection

You can also use pyCurl

import sys
import pycurl

class ContentCallback:
        def __init__(self):
                self.contents = ''

        def content_callback(self, buf):
                self.contents = self.contents + buf

t = ContentCallback()
curlObj = pycurl.Curl()
curlObj.setopt(curlObj.URL, 'http://www.google.com')
curlObj.setopt(curlObj.WRITEFUNCTION, t.content_callback)
curlObj.perform()
curlObj.close()
print t.contents

相关问题 更多 >