可复制代码如下:
###多线程
import re
import threading
import urllib.request
import urllib.error
import threading
headers=("User-Agent","Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36")
opener=urllib.request.build_opener()
opener.addheaders=[headers]
urllib.request.install_opener(opener)
class One(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
print("我是线程One")
for i in range(1,20,2):
url='https://www.qiushibaike.com/text/page/'
urla=url+str(i)
data=urllib.request.urlopen(urla).read().decode("utf-8","ignore")
pat='<div class="content">.*?<span>(.*?)</span>.*?</div>'
datalist=re.compile(pat,re.S).findall(data)
for j in range(0,len(datalist)):
print("第"+str(i)+"页第"+str(j)+"个段子的内容")
print(datalist[j])
class Two(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
print("我是线程Two")
for i in range(0,20,2):
url='https://www.qiushibaike.com/text/page/'
urla=url+str(i)
data=urllib.request.urlopen(urla).read().decode("utf-8","ignore")
pat='<div class="content">.*?<span>(.*?)</span>.*?</div>'
datalist=re.compile(pat,re.S).findall(data)
for j in range(0,len(datalist)):
print("第"+str(i)+"页第"+str(j)+"个段子的内容")
print(datalist[j])
one=One()
one.start()
two=Two()
two.start()
网友评论