老王Python-进阶篇4-多线程1.1

习题一:已知列表 info = [1,2,3,4,55,233],生成6个线程对象,每次线程输出一个值,最后输出:"the end"。

 1 import threading
 2 
 3 def test(j):
 4     print j
 5 
 6 ts=[]
 7 info = [1,2,3,4,55,233]
 8 for j in info:
 9     th=threading.Thread(target=test,args=[j])
10     th.start()
11     ts.append(th)
12 
13 for i in ts:
14     i.join()
15 
16 print 'end'

习题二:已知列表 urlinfo = ['http://www.sohu.com','http://www.163.com','http://www.sina.com'] 用多线程的方式分别打开列表里的URL,并且输出对应的网页标题和内容。

import urllib,re,threading

def func(url_new):
    try:
        f=urllib.urlopen(url_new)
    except IOError:
        print 'error'
    else:
        content= f.read()
        a=re.compile('<title>.*</title>')  #
        foundLabel = a.search(content)
        finalLabel=foundLabel.group()
        print content,finalLabel

if __name__=='__main__':
    url_list=['http://www.163.com','http://www.sina.com','http://www.sohu.com']

    ts=[]
    for j in url_list:
        th=threading.Thread(target=func,args=[j])
        th.start()
        ts.append(th)

    for i in ts:
        i.join()

    print 'end'

习题三:已知列表 urlinfo = ['http://www.sohu.com','http://www.163.com','http://www.sina.com'] 用多线程的方式分别打开列表里的URL,输出网页的http状态码

import urllib,re,threading

def func(url_new):
    try:
        f=urllib.urlopen(url_new)
    except IOError:
        print 'error'
    else:
        code=f.code
        content= f.read()
        a=re.compile('<title>.*</title>')  #正则表达式查找标题
        foundLabel = a.search(content)
        finalLabel=foundLabel.group()
        print [code],finalLabel

if __name__=='__main__':
    url_list=['http://www.163.com','http://www.sina.com','http://www.sohu.com']

    ts=[]
    for j in url_list:
        th=threading.Thread(target=func,args=[j])
        th.start()
        ts.append(th)

    for i in ts:
        i.join()

    print 'end'

 

posted @ 2018-01-17 22:44  秋刀鱼Q  阅读(227)  评论(0编辑  收藏  举报