【问题标题】:proxies and urls in python urllib2python urllib2中的代理和url
【发布时间】:2013-11-15 08:04:12
【问题描述】:

这是我的代码,但它给了我一些我无法解决的错误。即使相同的代码在单个 url 和单个代理上运行良好,但它没有为 proxy 和 urls 文件运行。

import urllib2
import time 
#bangalore, boston,china

with open('urls.txt') as f:
    urls = [line.strip() for line in f]
    print "list of urls",urls
with open('proxies.txt') as proxies:
    for proxy in proxies:
        print proxy
        proxy = proxy.rstrip()
        print proxy
        proxy_handler = urllib2.ProxyHandler(proxy)
        opener = urllib2.build_opener(proxy_handler)
        urllib2.install_opener(opener)
        try:
            for url in urls:
                request=urllib2.Request(url)
                start=time.time()
                try:
                    print "from try block"
                    response=urllib2.urlopen(urls[0])
                    response.read(1)
                    ttfb = time.time() - start
                    print "Latency:", ttfb
                    print "Status Code:", response.code
                    print "Headers:", response.headers
                    print "Redirected url:", response.url  
                except urllib2.URLError as e:
                    print "From except"
                    print "Error Reason:", e.reason
                    print "Error Message:", e.message
                   # print "Redirected URL:", e.url
                except urllib2.HTTPError as e:
                    print e.reason 
        except Exception,e:
            print e

【问题讨论】:

  • urls.txt 就像:'google.com' 和 proxies.txt 是:{'http':'ipaddress:8000'}
  • 您正在尝试将字符串加载到代理处理程序中,尝试使用 json.loads 加载 proxies.txt 中的行以创建 dict 对象。我认为格式也应该是 {"http" : "ip_address:port"}。可能还有其他问题
  • 还有response=urllib2.urlopen(urls[0]) 应该是response=urllib2.urlopen(url) ?
  • 是的..我认为这是打字错误。就像 resonse = urllib2.urlopen(url)
  • 正如你告诉我使用 json.load() 加载的上述内容已经尝试过的那样.. 它给我一个错误作为 obj, end = self.scan_once(s, idx) ValueError: Expecting属性名称:第 1 行第 2 列(字符 1)

标签: python python-2.7 proxy urllib2


【解决方案1】:

替换为:

proxy = json.loads(proxy.rstrip())

(并导入 json)

urls.txt 行是这样的:

http://www.google.com

proxies.txt 行如下:

{"http" : "http://ip:port"}

根据我对您帖子的评论,这将始终引用第一个网址:

response=urllib2.urlopen(urls[0])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-01
    • 1970-01-01
    • 2010-11-29
    • 2012-09-13
    • 1970-01-01
    • 2013-06-04
    • 2019-09-29
    • 1970-01-01
    相关资源
    最近更新 更多