2

I'm trying to webscrape a page of written reviews on Tripadvisor, but am encountering difficulties clicking on the "more" button that expands all the written reviews on the page. I've taken a look at similar queries (thank you Saurabh Gaur) but when the button is clicked using selenium this login page pops up.

login page photo

Is there a way to click on the "more" button without triggering this? Thank you! :)

from selenium import webdriver
import re
from bs4 import BeautifulSoup

def clicker(url):
    browser = webdriver.Firefox()
    browser.get(url)

    
    # Use regex to find that button link
    pageSource = browser.page_source
    soup = BeautifulSoup(pageSource, 'html.parser')

    # Example: soup.findAll(True, {'class': re.compile(r'\bclass1\b')})
    Regex = re.compile(r'.*\bmoreLink.ulBlueLinks.*')
    linkElem = soup.find('span', class_=Regex)['class']
    linkElem = '.'.join(linkElem[0:(len(linkElem)+1)])
    moreButton = 'span.' + linkElem

    print(moreButton)

    button = browser.find_element_by_css_selector(moreButton)
    print(button)
    
    browser.execute_script("arguments[0].click()", button) 
    
clicker('https://www.tripadvisor.com.sg/Hotel_Review-g295424-d1209362-Reviews-Residence_Spa_at_One_Only_Royal_Mirage_Dubai-Dubai_Emirate_of_Dubai.html')
 
Domoman
  • 25
  • 4
  • Please check this post - http://stackoverflow.com/questions/28371989/use-selenium-to-click-and-view-more-text – Solomon Vimal Oct 26 '16 at 06:19
  • Thanks for this! I've tried and it still doesn't work. I still get the login page. Is this some form of anti-scraping measure on their part? Please help! – Domoman Oct 26 '16 at 09:04

1 Answers1

1

Here is a sample code for your reference, you can use selenium with phantomjs and click on the button. I have used name attribute of the tag which is required in the function "find_element_by_name", you can modify this according to your requirement.

from urllib.request import urlopen
from urllib.error import HTTPError
from bs4 import BeautifulSoup
from selenium import webdriver
def openUrl(link):
    driver = webdriver.PhantomJS(
                executable_path='../../phantomjs/bin/phantomjs')
            try:
                driver.get(link)
            except HTTPError as e:
                print ('Error opening ' + link)
                continue
            try:
                bsObj = BeautifulSoup(driver.page_source)
            except AttributeError as e:
                return None

            try:
                elem1 = driver.find_element_by_name('checkAndShowAnswers')
                elem1.click()
            except:
                continue
Tarun Gupta
  • 504
  • 5
  • 11