1

I'm trying to scrape some data off of this site, and many other "wines" on this site, and am using selenium to do so as its a JS site. however, I'm finding that my code only sometimes works and other times it does not return any values even though nothing is changing.

I think I should use explicit waits with selenium to overcome this challenge, however I'm not sure how to integrate them, so any guidance on doing so would be helpful!

my code is

def ct_content(url):
    browser = webdriver.PhantomJS()
    browser.get(url)
    wait = WebDriverWait(driver, 10)
    html = browser.page_source
    html = lxml.html.fromstring(html)
    try:
        content = html.xpath('//a[starts-with(@href, "list.asp?Table=List")]/text()')
        browser.quit()
        return content
    except:
        browser.quit()
        return False

Thanks!

2

2 Answers 2

2

Try to use more specific XPath:

//ul[@class="twin_set_list"]//a/text()

Also there is no need to use lxml. Simply try:

from selenium.webdriver.support.ui import WebDriverWait as wait
from selenium.webdriver.support import expected_conditions as EC

data = [link.get_attribute('textContent') for link in wait(browser, 10).until(EC.presence_of_all_elements_located((By.XPATH, '//ul[@class="twin_set_list"]//a')))]
Sign up to request clarification or add additional context in comments.

15 Comments

the issue with not using waits is that content is only returned sometimes and other times it just returns an empty list for me.
Did you try above code? no kind of waits can help you to solve the issue as required data is already in initial HTML source...
yeah I tried it, worked first time, second time it returned an empty list
second time == on another page?
Hmm... This is weird. Ok. Try updated answer with explicitWait applied
|
0

It looks like you never actually use the implicit wait. This is how I would write script with an explicit wait.

def ct_content(url):
    browser = webdriver.PhantomJS()
    browser.get(url)
    wait = WebDriverWait(browser, 10)
    try:
        content = wait.until(EC.element_to_be_clicable((By.XPATH, '//a[starts-with(@href, "list.asp?Table=List")]')))
        browser.quit()
        return content.text
    except:
        browser.quit()
        return False

Also, the way to set implicit waits is:

browser.implicitly_wait(10) # seconds

4 Comments

It also looks like you never use ExplicitWait... Your code is wrong!
My bad, I changed the non existent driver variable to browser, and added the missing closing paren. Is this any better? If not what's happening?
@Andersson content = wait.until(...) uses the explicit wait, no?
content = wait.until(...) looks like ExplicitWait... Can you tell us what is xpath() method and how it should work?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.