简体   繁体   中英

How to write this if statement in python/selenium/scraping

I have a trouble scraping the website because some of the same elements are just in a different class_name. So im trying to create a if statement to search the class first and if its not present it would move on to next class.

            driver.get("https://wormbase.org/#012-34-5")
            search = driver.find_element_by_id("Search")
            search.send_keys(cdi)
            search.send_keys(Keys.RETURN)

for this part i would like to add an if statement saying if id1 is not present then move on the id

            if id1 =! : # still not sure how to create the if statement

            id = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CLASS_NAME, "locus")))
            id1 = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CLASS_NAME, "highlight")))

            
            description = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CLASS_NAME, "text-min")))

            data['Gene_name'] = id.text
            data['Description'] = description.text

if you want to use if statement you have to use

find_elements_by_id("some id")

instead of

find_element_by_id("some id")

in this case you will have list with one element if the required element is present on the page and empty list if not.

ids = driver.find_elements_by_id("some id")
if ids:
    # do something fo example
    ids[0].click()
else:
    # try to search it again or do something else

First, find the length by using:

elementLength=driver.find_elements_by_id("id")

Then, if len(elementLength)>0 , go to the first class, and otherwise go to another.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM