1

I have an issue with Python control flow.Below is the scenario i'm trying get some data from a webpage using selenium.

Here is a sample part of the code that i'm using.I'm taking the list of URL's from database. So for each URL the chrome browser(same browser) will be opened and search for the URL page which is passed.

If there is nothing or no details on the URL page , ie when variable "length" is zero , i have modified the URL value by adding 'sell' to the URL and now i want to break the execution of the program and pass this new URL to "browser.get(url)" here without taking the next element from for loop.

for row in urls:
    url=str(row)

    browser.get(url)

    names = browser.find_elements_by_xpath("//span[@class='pymv4e']")
    product = [x.text for x in names]
    filtered = [x for x in product if len(x.strip()) > 0]
    length=(len(filtered))

    if length ==0 :
        url=url+ '+sell'
2
  • What's in filtered, where is it from? MVCE Commented Jan 22, 2020 at 12:11
  • @deadvoid Modified the script, it was the length of products after removing SPACE. Commented Jan 22, 2020 at 12:14

1 Answer 1

2

Quite simply: extract the relevant part of the code into a dedicated function, and re-call this function:

def get_products(url):
    browser.get(url)
    names = browser.find_elements_by_xpath("//span[@class='pymv4e']")
    # simplified the filtering
    # note that python objects have a "truth" value, 
    # and that empty strings and empty lists have a False value
    product = [x.text for x in names if x.text.strip()]


for row in urls:
    url = str(row) # XXX why do you need this ???
    products = get_products(url)
    if not products:
        url += '+sell'
        products = get_products(url)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.