Python 下载网页源代码

12 投票
5 回答
31083 浏览
提问于 2025-04-16 05:36

你好啊,我在想是否可以连接到一个HTTP主机(比如说google.com),然后下载这个网页的源代码呢?

提前谢谢你。

5 个回答

2

httplib(低级库)和urllib(高级库)的文档可以帮助你入门。你可以选择一个更适合你的库来使用。

7

你可以使用 urllib2 这个模块。

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

想要更多例子,可以查看文档。

14

使用urllib2下载网页。

谷歌会阻止这个请求,因为它会试图阻止所有机器人。你需要在请求中添加用户代理。

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

你也可以使用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

撰写回答