多線程爬蟲:即程式中的某些程式段並行執行,合理地設置多線程,可以讓爬蟲效率更高糗事百科段子普通爬蟲和多線程爬蟲分析該網址鏈接得出:https://www.qiushibaike.com/8hr/page/頁碼/多線程爬蟲也就和JAVA的多線程差不多,直接上代碼 1 ''' 2 #此處代碼為普通爬蟲 ... ...
多線程爬蟲:即程式中的某些程式段並行執行,
合理地設置多線程,可以讓爬蟲效率更高
糗事百科段子普通爬蟲和多線程爬蟲
分析該網址鏈接得出:
https://www.qiushibaike.com/8hr/page/頁碼/
多線程爬蟲也就和JAVA的多線程差不多,直接上代碼
1 ''' 2 #此處代碼為普通爬蟲 3 import urllib.request 4 import urllib.error 5 import re 6 7 headers = ("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36") 8 opener = urllib.request.build_opener() 9 opener.addheaders = [headers] 10 urllib.request.install_opener(opener) 11 for i in range(1,2): 12 url = "https://www.qiushibaike.com/8hr/page/"+str(i)+"/" 13 pagedata = urllib.request.urlopen(url).read().decode("utf-8","ignore") 14 pattern = '<div class="content">.*?<span>(.*?)</span>(.*?)</div>' 15 datalist = re.compile(pattern,re.S).findall(pagedata) 16 for j in range(0,len(datalist)): 17 print("第"+str(i)+"頁第"+str(j)+"個段子內容是:") 18 print(datalist[j]) 19 ''' 20 21 ''' 22 #此處為多線程介紹代碼 23 import threading #導入多線程包 24 class A(threading.Thread): #創建一個多線程A 25 def __init__(self): #必須包含的兩個方法之一:初始化線程 26 threading.Thread.__init__(self) 27 def run(self): #必須包含的兩個方法之一:線程運行方法 28 for i in range(0,11): 29 print("我是線程A") 30 31 class B(threading.Thread): #創建一個多線程A 32 def __init__(self): #必須包含的兩個方法之一:初始化線程 33 threading.Thread.__init__(self) 34 def run(self): #必須包含的兩個方法之一:線程運行方法 35 for i in range(0,11): 36 print("我是線程B") 37 38 t1 = A() #線程實例化 39 t1.start() #線程運行 40 t2 = B() 41 t2.start() 42 ''' 43 44 45 #此處為修改後的多線程爬蟲 46 #使用多線程進行奇偶頁的爬取 47 import urllib.request 48 import urllib.error 49 import re 50 import threading 51 52 headers = ("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36") 53 opener = urllib.request.build_opener() 54 opener.addheaders = [headers] 55 urllib.request.install_opener(opener) 56 class one(threading.Thread): #爬取奇數頁內容 57 def __init__(self): 58 threading.Thread.__init__(self) 59 def run(self): 60 for i in range(1,12,2): 61 url = "https://www.qiushibaike.com/8hr/page/"+str(i)+"/" 62 pagedata = urllib.request.urlopen(url).read().decode("utf-8","ignore") 63 pattern = '<div class="content">.*?<span>(.*?)</span>(.*?)</div>' 64 datalist = re.compile(pattern,re.S).findall(pagedata) 65 for j in range(0,len(datalist)): 66 print("第"+str(i)+"頁第"+str(j)+"段子內容為:") 67 print(datalist[j]) 68 69 70 class two(threading.Thread): #爬取奇數頁內容 71 def __init__(self): 72 threading.Thread.__init__(self) 73 def run(self): 74 for i in range(2,12,2): 75 url = "https://www.qiushibaike.com/8hr/page/"+str(i)+"/" 76 pagedata = urllib.request.urlopen(url).read().decode("utf-8","ignore") 77 pattern = '<div class="content">.*?<span>(.*?)</span>(.*?)</div>' 78 datalist = re.compile(pattern,re.S).findall(pagedata) 79 for j in range(0,len(datalist)): 80 print("第"+str(i)+"頁第"+str(j)+"段子內容為:") 81 print(datalist[j]) 82 t1 = one() 83 t2 = two() 84 t1.start() 85 t2.start()