3
votes

I'm trying to scrape using Python dynamic content which is generated in JavaScript (the number of views and comments on this video: http://v.youku.com/v_show/id_XMTM5NTI3NDY3Ng==.html?from=y1.3-idx-uhome-1519-20887.205805-205902.5-2).

I'm familiar with BeautifulSoup (runs in ~0.1 seconds, but no JavaScript evaluation) and Selenium (3+ seconds, even when I deactivate CSS, images, etc., but interprets JS).

Is there a way to scrape the result of a JavaScript function in Python without actually using a browser (assuming that is what slows down Selenium)?

My Selenium code is below:

# coding=utf-8

import time
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait 
from selenium.webdriver.common.keys import Keys

firefox_profile=webdriver.FirefoxProfile()
#firefox_profile.set_preference('permissions.default.stylesheet',2)
firefox_profile.set_preference('permissions.default.image',2)
firefox_profile.set_preference('dom.ipc.plugins.enabled.libflashplayer.so',2)
driver = webdriver.Firefox(firefox_profile=firefox_profile)
time.sleep(7)

start=time.time()
def getYoukuVideoStats(youkuVideoUrl):
    driver.get(youkuVideoUrl)
    text= driver.find_element_by_id("allnum_cmt").text
    print text

youku_video_urls_full=["http://v.youku.com/v_show/id_XOTU2Nzc3NDYw.html"]

for youkuVideoUrl in youku_video_urls_full:
    try:
        getYoukuVideoStats(youkuVideoUrl)
        print youkuVideoUrl
    except Exception, e:
        print "Error with video: "+youkuVideoUrl
        print str(e)

print time.time()-start
3

3 Answers

4
votes

You do need to use a browser to render the JS but you can use a headless browser such as phantomjs. This will speed up your run time and you won't see the browser open.

3
votes

No, there's no way to scrape the result of js code without using a browser whether it be a visible or invisible (phantomjs) one.

3
votes

You could also use splash which makes javascript rendering easy, making it like a service, so you keep using it like crawling a normal website.

It plays really well with scrapy for python web-scraping.