user1915050
user1915050

Reputation:

Issues with invoking "on click event" on the html page using beautiful soup in Python

I am trying to scrape names of all the items present on the webpage but by default only 18 are visible on the page & my code is scraping only those. You can view all items by clicking on "Show all" button but that button is in Javascript.

After some research, I found that PyQt module can be used to solve this issue involving javascript buttons & I used it but I am still not able to invoke the "on click" event. Below is the referred code:

import csv
import urllib2
import sys
import time
from bs4 import BeautifulSoup
from PyQt4.QtGui import *  
from PyQt4.QtCore import *  
from PyQt4.QtWebKit import *  

class Render(QWebPage):  
  def __init__(self, url):  
    self.app = QApplication(sys.argv)  
    QWebPage.__init__(self)  
    self.loadFinished.connect(self._loadFinished)  
    self.mainFrame().load(QUrl(url))  
    self.app.exec_()  

  def _loadFinished(self, result):  
    self.frame = self.mainFrame()  
    self.app.quit()  

url = 'http://www.att.com/shop/wireless/devices/smartphones.html'  
r = Render(url)
jsClick = var evObj = document.createEvent('MouseEvents');
             evObj.initEvent('click', true, true );
             this.dispatchEvent(evObj);


allSelector = "a#deviceShowAllLink" # This is the css selector you actually need
allButton   = r.frame.documentElement().findFirst(allSelector)
allButton.evaluateJavaScript(jsClick)




page = allButton
soup = BeautifulSoup(page)
soup.prettify()
with open('Smartphones_26decv1.0.csv', 'wb') as csvfile:
    spamwriter = csv.writer(csvfile, delimiter=',')
    spamwriter.writerow(["Date","Day of Week","Device Name","Price"])
    items = soup.findAll('a', {"class": "clickStreamSingleItem"},text=True)
    prices = soup.findAll('div', {"class": "listGrid-price"})
    for item, price in zip(items, prices):
        textcontent = u' '.join(price.stripped_strings)
        if textcontent:            
            spamwriter.writerow([time.strftime("%Y-%m-%d"),time.strftime("%A") ,unicode(item.string).encode('utf8').strip(),textcontent])

Error which I am facing in this is as follows:

"Invalid Syntax" Error for evObj

Can someone please help me in invoking this "onclick" event so that I am able to scrape data for all items.Pardon me for my ignorance as I am new to programming.

Upvotes: 4

Views: 6516

Answers (2)

Joseph Thomas
Joseph Thomas

Reputation: 494

from contextlib import closing
from selenium.webdriver import Firefox # pip install selenium
from selenium.webdriver.support.ui import WebDriverWait
from BeautifulSoup import BeautifulSoup
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
# use firefox to get page with javascript generated content
with closing(Firefox()) as driver:
    driver.get("http://www.att.com/shop/wireless/devices/smartphones.html")
    button = driver.find_element_by_id('deviceShowAllLink')
    button.click()
    # wait for the page to load
    element = WebDriverWait(driver, 10).until(
    EC.invisibility_of_element_located((By.ID, "deviceShowAllLink"))
    )
    # store it to string variable
    page_source = driver.page_source

soup = BeautifulSoup(page_source)
items = soup.findAll('div', {"class": "list-item"})
print "items count:",len(items)

will this help..?

Upvotes: 2

user1006989
user1006989

Reputation:

To click the button you must call evaluateJavascript over the object:

jsClick = """var evObj = document.createEvent('MouseEvents');
             evObj.initEvent('click', true, true );
             this.dispatchEvent(evObj);
             """

allSelector = "a#deviceShowAllLink" # This is the css selector you actually need
allButton   = r.frame.documentElement().findFirst(allSelector)
allButton.evaluateJavaScript(jsClick)

Upvotes: 1

Related Questions