简体   繁体   中英

Python Selenium attribute value

I need the value for attribute with the name "serial" which I am unable to get with my limited skills in python & selenium. I am looking for the output of "0000013". and please guide me how to capture the element in a loop as well. many thanks.

What I have tried:

for data in soup.find_all(class_='CoreData'):
    h = data.find('h2')
    k = h.find('serial')
    print(k)

It returns value of "None" instead of the value of "Serial"

<h2>                        <!--For Verified item-->
                                        <a class="clickable" style="cursor:pointer;" onmousedown="open_item_detail('0000013', '0', false)" id="View item Detail" serial="0000013">
                                            Sample Item
                                        </a>
                                    <!--For unverified item-->
                                </h2>

To get the value of serial , try the following:

from bs4 import BeautifulSoup

html = """
<h2>
 <!--For Verified item-->
 <a class="clickable" id="View item Detail" onmousedown="open_item_detail('0000013', '0', false)" serial="0000013" style="cursor:pointer;">
  Sample Item
 </a>
 <!--For unverified item-->
</h2>"""

soup = BeautifulSoup(html, "html.parser")

for data in soup.find_all("a", class_="clickable"):
    print(data["serial"])

Output:

0000013

To print the value of the attribute serial ie 0000013 you need to induce WebDriverWait for the visibility_of_element_located() and you can use either of the following Locator Strategies :

  • Using CSS_SELECTOR :

     print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "h2 a.clickable[onmousedown^='open_item_detail']"))).get_attribute("data-clipboard-text"))
  • Using XPATH :

     print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//h2//a[@class='clickable' and starts-with(@onmousedown, 'open_item_detail')]"))).get_attribute("serial"))
  • Note : You have to add the following imports :

     from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC

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