Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing conditional imports as a way to utilize different functions with the same namespace
    text
    copied!<p>I am a beginner python programmer, and I am working on a selenium project in python 2.7. </p> <p>I have a generic scraper script, that basically outlines what I want to do with all the websites that I visit. However, because of the nature of the data that I want to grab, I can't run the same code on each site-- each site needs to run it's own individual code. </p> <p>I have attempted to solve this by importing inside of an if statement, and this is the solution I came up with: </p> <pre><code>site = False if source_website == "Website A": from website_a import * site = True elif source_website == "Website B": from website_b import * site = True else: print "This is not an acceptable website!" if site == True: # main code block driver = driver_setup(chrome) driver.get(source_website_URL) stuff_to_save = do_some_stuff(driver) xml_file(stuff_to_save) driver.quit() </code></pre> <p>where the <code>website_a</code> and <code>website_b</code> modules both have functions named <code>do_some_stuff</code>, and they do stuff specific to the website that they're on. Now, this seems to work, for the most part. I also seem to be able to extend functionality to any number of websites, given that I program a module called <code>website_c</code> with the function <code>do_some_stuff</code>, and add that to the conditional import.</p> <p>So, my question is, is this a good idea? Is there a better way to do something like this?</p> <p>I have literally never seen anyone wrap import statements inside of if statements like this-- and generally, if no one seems to do it, there's usually a good reason why. </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload