import os
from threading import Thread
from queue import Queue # 导入队列库
from fake_useragent import UserAgent
path = os.getcwd() + "/fake_useragent_0.1.11.json"
ua = UserAgent(path=path)
import requests
from time import sleep
def xiancheng():
# 如果不为空,则往下执行 非空则退出循环,下面已经扔进去数据了,所以不为空
#只要里面有数据,它就会不停的拿
while not urlque.empty():
url = urlque.get() #拿出urlque放入队列里的
print(f'正在获取{url}页面数据')
#print(f'正在获取第{i}页数据')
headers = {'User-Agent': ua.chrome}
resp = requests.get(url, headers=headers)
#获取resp的json格式 get数据里data的内容
for d in resp.json().get('data'):
print(f'标题:{d.get("topicName")} id:{d.get("tid")} content:{d.get("content")}')
sleep(3)
#返回码是不是200 不是二百为错误
if resp.status_code==200:
print(f'成功获取第{url}页数据')
if __name__ == '__main__':
# 创建一个队列,不然多线程每次拿的都是同一个数据
urlque = Queue()
for i in range(1, 11): #对网页页数进行遍历生成多页网址
url = f'https://www.hupu.com/home/v1/news?pageNo={i}&pageSize=50'
urlque.put(url) # 把生成的网址扔进url队列,上面线程get取走就可以了
for a in range(5): #创建多少线程
t1 = Thread(target=xiancheng)
t1.start()