【发布时间】:2018-04-01 01:48:06
【问题描述】:
我已经编写了一个python脚本来打开arround 1k url并对其进行处理以获得所需的结果,但似乎即使引入了多线程它的工作速度也很慢,并且在处理了一些url之后,该过程似乎被挂起,我无法确定它是否仍在运行或停止。如何创建多个线程以更快地处理它们。任何帮助将不胜感激。在此先感谢。下面是我的脚本。
import threading
from multiprocessing.pool import ThreadPool
from selenium import webdriver
from selenium.webdriver.phantomjs.service import Service
from selenium.webdriver.common.desired_capabilities import
DesiredCapabilities
from selenium.webdriver.remote.webdriver import WebDriver as
RemoteWebDriver
from multiprocessing.dummy import Pool # This is a thread-based Pool
from multiprocessing import cpu_count
import csv
def fetch_url(url):
driver = webdriver.PhantomJS()
driver.get(url)
html = driver.page_source
print(html)
print("'%s\' fetched in %ss" % (url[0], (time.time() - start)))
def thread_task(lock,data_set):
lock.acquire()
fetch_url(url)
lock.release()
if __name__ == "__main__":
data_set = []
with open('file.csv', 'r') as csvfile:
spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
for row in spamreader:
data_set.append(row)
lock = threading.Lock()
# data set will contain a list of 1k urls
for url in data_set:
t1 = threading.Thread(target=thread_task, args=(lock,url,))
# start threads
t1.start()
# wait until threads finish their job
t1.join()
print("Elapsed Time: %s" % (time.time() - start))
【问题讨论】:
-
您正在使用一个锁进行所有处理。你为什么要使用锁?
-
我可能会推荐使用当前执行此操作的 requests_futures
-
嗨,Alex,我的系统在运行多个线程时变得很慢,因为我们可以在这里看到它为每个 url 创建一个线程,因此我添加了锁。让我知道我需要做任何更改。
-
嗨 Shailyn,我对 requests_futures 没有任何想法,您能否通过一些示例让我了解更多信息。
标签: python multithreading