如何在其他函数中使用局部变量?

2024-04-20 03:30:59 发布

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

我想在一个单独的函数中打印结果,但是当我调用变量时,我不能使用它们,因为它们在不同的函数中。有人能告诉我如何编辑我的代码让它工作吗?p、 我知道我应该用美肌。。。然而,我有麻烦得到它安装在我的电脑上

import urllib2
from urllib2 import urlopen
import re
import cookielib
from cookielib import CookieJar
import time
c_j = CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(c_j))
opener.addheaders = [('User-agent','Mozilla/5.0')] #Makes the website think we are       using firefox by using header

def proxies1():
      try:
          page = 'http://free-proxy-list.net/' #Sets the variable page as our website
          sourceCode = opener.open(page).read() #Reads the source code
          titles = re.findall('<tr><td>(.*?)</td><td>', sourceCode) #Parses the Html, collects the proxies
     for title in titles:
         proxy1 = title.replace(',', '').replace("!", '').replace(":", '').replace(";", '') 
     except Exception, e:

         print str(e)

def ports1():
      try:
        page = 'http://free-proxy-list.net/' #Sets the variable page as our website
        sourceCode = opener.open(page).read() #Reads the source code
        banana = re.findall('</td><td>(.*?)</td><td>', sourceCode) #Parses the Html, collects the proxies
        for title in banana:
              port1 = title.replace('a', '').replace('b', '').replace('c', '').replace('d', '').replace('e', '').replace('f', '').replace('g', '').replace('h', '') \
  .replace('i', '').replace('j', '').replace('k', '').replace('l', '').replace('m', '').replace('n', '').replace('o', '').replace('p', '') \
  .replace('q', '').replace('r', '').replace('s', '').replace('t', '').replace('u', '').replace('v', '').replace('w', '').replace('x', '') \
  .replace('y', '').replace('z', '').replace('A', '').replace('B', '').replace('C', '').replace('D', '').replace('E', '').replace('F', '').replace('G', '') \
  .replace('H', '').replace('I', '').replace('J', '').replace('K', '').replace('L', '').replace('M', '').replace('N', '').replace('O', '') \
  .replace('P', '').replace('Q', '').replace('R', '').replace('S', '').replace('T', '').replace('U', '').replace('V', '').replace('W', '') \
  .replace('X', '').replace('Y', '').replace('Z', '')
  except Exception, e:
    print str(e)



def printfun():

      print str(proxy1) + ":" + str(port1)

printfun()

我知道我的缩进有点偏了,堆栈溢出把它搞砸了。。。。我该怎么做?你知道吗


Tags: the函数importretitledefpagewebsite
2条回答

你想打印一份代理:端口地址? 这将有助于:

import urllib2
from urllib2 import urlopen
import re
import cookielib
from cookielib import CookieJar
import time
c_j = CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(c_j))
opener.addheaders = [('User-agent','Mozilla/5.0')]

def proxies():
      page = 'http://free-proxy-list.net/'
      sourceCode = opener.open(page).read()
      proxy_ports = re.findall('<tr><td>(.*?)</td><td>(.*?)</td><td>', sourceCode)
      addresses = []
      for pp in proxy_ports:
            addresses.append("%s:%s" % pp)
      return addresses

print "\n".join(proxies())

不能在另一个函数中使用来自一个函数的局部变量。也就是说,事实上,局部变量的整个。你知道吗

你可以用全局变量来改变事情,但那是个坏主意。你知道吗

然而,一个类似的想法是使用对象属性,虽然有相同的好处,但没有问题。将这两个函数更改为类的方法,并将变量更改为该类的属性。像这样:

class ProxyParser(object):
    def proxies1(self):
          try:
              self.page = 'http://free-proxy-list.net/' #Sets the variable page as our website
              self.sourceCode = opener.open(page).read() #Reads the source code
              self.titles = re.findall('<tr><td>(.*?)</td><td>', sourceCode) #Parses the Html, collects the proxies
         for title in self.titles:
             proxy1 = title.replace(',', '').replace("!", '').replace(":", '').replace(";", '') 
         except Exception, e:

             print str(e)
def ports1(self):
    try:
        for title in self.titles:
            # etc.

proxy_parser = ProxyParser()
proxy_parser.proxies1()
proxy_parser.ports1()

基本上,只要在每个函数的参数列表的开始处粘贴一个self,在每个局部变量之前粘贴一个self.,现在它们是实例变量,由该对象的所有方法共享,而不是每个单独的函数的局部变量。你知道吗


另一种方法是从一个函数中获取return值,然后将它们作为参数传递给另一个函数。像这样:

def proxies1():
      try:
          page = 'http://free-proxy-list.net/' #Sets the variable page as our website
          sourceCode = opener.open(page).read() #Reads the source code
          titles = re.findall('<tr><td>(.*?)</td><td>', sourceCode) #Parses the Html, collects the proxies
     for title in titles:
         proxy1 = title.replace(',', '').replace("!", '').replace(":", '').replace(";", '')
     except Exception, e:

         print str(e)
     return titles

def ports1(titles):
    for title in titles:
         # etc.

titles = proxies1()
ports1(titles)

同时,当你问到在另一个函数中使用一个函数的变量时,我认为你实际上想要的是在两个函数之外使用它们。幸运的是,完全相同的解决方案同样适用于此:要么return您想要使用的值,要么将它们存储为实例属性。你知道吗

然而,在你能到达那里之前…你必须实际拥有你想要的值。你的proxies函数只是一遍又一遍地重新定义proxy1变量。所以,即使你return proxy1,它也只是页面中的最后一个。同样,您的ports1函数对port1也做了同样的处理。你知道吗

我仍然不确定您到底想在这里做什么,但可能您想返回所有代理。你可以通过建立一个列表并返回它,或者,如果你想冒险的话,可以对每个列表进行yield。然后,调用者可以从一个函数获取代理列表(或迭代器),从另一个函数获取端口列表(或迭代器),将它们放在一起,并循环返回结果。像这样:

proxies = proxies1()
ports = ports1()
for proxy, port in zip(proxies, ports):
    print proxy + ':' + port

相关问题 更多 >