1 Star 0 Fork 0

时箭匆嵘/scrapy_study

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
pachong&thread1205.py 2.29 KB
一键复制 编辑 原始数据 按行查看 历史
时箭匆嵘 提交于 2017-12-06 17:24 . 学习mongoDB
#--coding='utf-8'--
import requests
from bs4 import BeautifulSoup
import threading
import queue
import time
class Crawl():
def __init__(self):
self.UA = ("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 "
"(KHTML, like Gecko) Chrome/49.0.2623.75 Safari/537.36 LBBROWSER")
def parse(self,url):
items = []
r = requests.get(url,headers = {"User-Agent":self.UA})
html = r.content
soup = BeautifulSoup(html,"html.parser")
titles = soup.findAll("a", class_='name')
for title in titles:
items.append(title.string)
return items
class mythread(threading.Thread):
def __init__(self,threadname,queue):
threading.Thread.__init__(self)
self.threadname = threadname
self.queue = queue
def run(self):
print("Thread {0} is running!".format(self.threadname))
# threadLock.acquire()
process_data(self.threadname,self.queue)
# threadLock.release()
print("Thread {0} is done!".format(self.threadname),time.ctime(time.time()))
time.sleep(1)
def process_data(threadname,queue):
while not exitflag:
threadLock.acquire()
if not queue.empty():
url = queue.get()
crawl1 = Crawl()
item = crawl1.parse(url)
threadLock.release()
print("------------------------------------------------------")
for i in item:
print(threadname, i)
else:
threadLock.release()
if __name__ == "__main__":
exitflag = 0
threadList = ["No.1", "No.2", "No.3"]
threadLock = threading.Lock()
urlList = ['https://www.qidian.com/kehuan','https://www.qidian.com/lishi',
'https://www.qidian.com/junshi','https://www.qidian.com/wuxia','https://www.qidian.com/youxi']
threads = []
parseQueue = queue.Queue(6)
# 填充队列
threadLock.acquire()
for url in urlList:
parseQueue.put(url)
threadLock.release()
# 创建新线程
for name in threadList:
thread = mythread(name, parseQueue)
thread.start()
threads.append(thread)
# 等待队列清空
while not parseQueue.empty():
pass
# 通知线程退出
exitflag = 1
for th in threads:
th.join()
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/ShiJianCongRong/scrapy_study.git
[email protected]:ShiJianCongRong/scrapy_study.git
ShiJianCongRong
scrapy_study
scrapy_study
master

搜索帮助