day10_ Multithreading 3

Source: Internet
Author: User

# Multi-threaded to write six Web sites into a file (parallel)

Import requests,time,threading

def write_html (url,name):

r = Requests.get (URL)

With open (name, ' W ', encoding = ' UTF8 ') as F:

F.write (R.text)

urls = [' www.nnzhp.cn ', ' www.besttest.cn ', ' www.imdsx.cn ', ' sb.nnzhp.cn ',' bbs.besttest.cn ', ' Video.besttest.cn '] #六个网站URL

Lis = [] # Store each thread

Start_time = Time.time ()

For URL in URLs: # Loop each URL

new_file = '/http ' + URL

file_name = URL + '. html '

t = Threading. Thread (target = Write_html,args = (new_url,file_name)) # instantiates a thread

Lis.append (t)

T.start () # Start a thread

# Start six threads, let them run, the main thread waits for them, join is the main thread waiting for each sub-thread to finish executing

For obj in Lis:

Obj.join () # Join must be placed outside of the six threads that are started

End_time = Time.time ()

Print (' program runs in total ', end_time-start_time)

The main thread waits for the child thread to crawl all the pages and then the main thread to send the message

day10_ Multithreading 3

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.