gpt4 book ai didi

Python http下载页面源码

转载 作者:太空狗 更新时间:2023-10-29 20:36:50 25 4
gpt4 key购买 nike

你好我想知道是否可以连接到 http 主机(例如 google.com)并下载网页源码?

提前致谢。

最佳答案

Using urllib2 to download a page.

Google 将阻止此请求,因为它会尝试阻止所有机器人。将用户代理添加到请求中。

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

关于Python http下载页面源码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3949744/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com