简体   繁体   English

Python-打印第二个参数

[英]Python - print 2nd argument

I am new to Python and I've written this test-code for practicing purposes, in order to find and print email addresses from various web pages: 我是Python的新手,出于实践目的,我编写了此测试代码,以便从各种网页中查找和打印电子邮件地址:

def FindEmails(*urls):
    for i in urls:
         totalemails = []
         req = urllib2.Request(i)
         aResp = urllib2.urlopen(req)
         webpage = aResp.read()
         patt1 = '(\w+[-\w]\w+@\w+[.]\w+[.\w+]\w+)'
         patt2 = '(\w+[\w]\w+@\w+[.]\w+)'
         regexlist = [patt1,patt2]
         for regex in regexlist:
             match = re.search(regex,webpage)
             if match:
                 totalemails.append(match.group())
                 break
    #return totalemails
    print "Mails from webpages are: %s  " % totalemails

if __name__== "__main__":
    FindEmails('https://www.urltest1.com', 'https://www.urltest2.com')

When I run it, it prints only one argument. 当我运行它时,它仅输出一个参数。 My goal is to print the emails acquired from webpages and store them in a list, separated by commas. 我的目标是打印从网页获取的电子邮件并将其存储在列表中,并以逗号分隔。

Thanks in advance. 提前致谢。

The problem here is the line: totalemails = [] . 这里的问题是这一行: totalemails = [] Here, you are re-instantiating the the variables totalemails to have zero entries. 在这里,您重新实例化了totalemails变量, totalemails具有零项。 So, in each iteration, it only has one entry inside it. 因此,在每次迭代中,它内部只有一个条目。 After the last iteration, you'll end up with just the last entry in the list. 在最后一次迭代之后,您将只获得列表中的最后一个条目。 To get a list of all emails, you need to put the variable outside of the for loop. 要获得所有电子邮件的列表,您需要将变量放在for循环之外。 Example: 例:

def FindEmails(*urls):
    totalemails = []
    for i in urls:
         req = urllib2.Request(i)
         ....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM