我正在使用Python和Scrapy製作網絡爬蟲/刮板。由於一些網站動態加載其內容,我還將Selenium與PhantomJs結合使用。現在當我開始使用這個時,我認爲表演會是可以接受的,但是結果很慢。現在我不確定這是因爲我的代碼中存在漏洞,還是因爲我使用的框架/程序不夠優化。所以我問你們關於我能做些什麼來改善表現的建議。
我寫的代碼大約需要。 35秒開始和結束。它正在執行大約11個GET請求和3個Post請求。Python/Scrapy/Selenium/PhantomJs - 性能
import scrapy
from scrapy.http.request import Request
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
import time
class TechcrunchSpider(scrapy.Spider):
name = "techcrunch_spider_performance"
allowed_domains = ['techcrunch.com']
start_urls = ['https://techcrunch.com/search/heartbleed']
def __init__(self):
self.driver = webdriver.PhantomJS()
self.driver.set_window_size(1120, 550)
#self.driver = webdriver.Chrome("C:\Users\Daniel\Desktop\Sonstiges\chromedriver.exe")
self.driver.wait = WebDriverWait(self.driver, 5) #wartet bis zu 5 sekunden
def parse(self, response):
start = time.time() #ZEITMESSUNG
self.driver.get(response.url)
#wartet bis zu 5 sekunden(oben definiert) auf den eintritt der condition, danach schmeist er den TimeoutException error
try:
self.driver.wait.until(EC.presence_of_element_located(
(By.CLASS_NAME, "block-content")))
print("Found : block-content")
except TimeoutException:
self.driver.close()
print(" block-content NOT FOUND IN TECHCRUNCH !!!")
#Crawle durch Javascript erstellte Inhalte mit Selenium
ahref = self.driver.find_elements(By.XPATH,'//h2[@class="post-title st-result-title"]/a')
hreflist = []
#Alle Links zu den jeweiligen Artikeln sammeln
for elem in ahref :
hreflist.append(elem.get_attribute("href"))
for elem in hreflist :
print(elem)
print("im closing myself")
self.driver.close()
end = time.time()
print("Time elapsed : ")
finaltime = end-start
print(finaltime)
我使用Windows 8 64位,英特爾i7-3630QM CPU @ 2,4GHZ的NVIDIA GeForce GT 650M,8GB的內存。
PS:對於德國評論感到抱歉
您可以嘗試通過您的蜘蛛生成AJAX請求,從而消除了對Selenium的需求,並且無需等待5秒鐘即可加載頁面。檢查此[頻繁發佈](https://stackoverflow.com/questions/8550114/can-scrapy-be-used-to-scrape-dynamic-content-from-websites-that-are-using-ajax)。 – rongon
閱讀這個問題的答案https://stackoverflow.com/questions/39036137/how-yo-make-a-selenium-scripts-faster – parik