在Python中打开URL

2024-04-25 06:30:30 发布

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

如何在Python中打开包含变量和键值的URL? 我尝试了如下,但我收到了400个错误的请求。在我的网络浏览器中打开文件(主机)似乎没有任何问题。也许是代理人?在

for verb in verbs:
    host = 'http://google.no/blabla?text=' + verb + '&pos=Any'
    checktext = '<font color="maroon">' + verb + '</font>'

    params = {'http': 'http://www.someproxy.com:3128'}

    req = urllib2.Request(host, urllib.urlencode(params))
    res = urllib2.urlopen(req)

    print res.read()

明白了。当我把None作为req中的第二个参数时(urllib.urlencode(params)),它起作用。所以,它一定是服务器不喜欢的代理。


Tags: 网络httphosturl错误浏览器resparams
2条回答

尝试使用urllib2.build\u打开程序:

import urllib2,cookielib

opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookielib.CookieJar()))
url = 'http://google.no/blabla'

for verb in verbs:
    data = '?text=' + verb + '&pos=Any' # not really sure how to fit your 'params' in here
    socket = opener.open(url,data)
    print socket.read()

我不知道你在那里做什么。urllib2.Request的第二个参数是要发送到服务器的数据。在

使用Request设置代理的方法是调用req.set_proxy(host, type)-请参见the documentation。在

相关问题 更多 >