【问题标题】:Python Selenium attribute valuePython Selenium 属性值
【发布时间】:2021-03-01 04:48:28
【问题描述】:

我需要名称为“serial”的属性值,但我在 python 和 selenium 方面的技能有限,无法获得该值。我正在寻找“0000013”的输出。并请指导我如何在循环中捕获元素。非常感谢。

我尝试过的:

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

它返回“None”的值而不是“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>

【问题讨论】:

  • 我没有看到课程CoreData。请更新更多 HTML 和您尝试过的完整代码

标签: python selenium xpath beautifulsoup webdriverwait


【解决方案1】:

要获取serial 的值,请尝试以下操作:

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"])

输出:

0000013

【讨论】:

    【解决方案2】:

    要打印属性serial 的值,即0000013,您需要为visibility_of_element_located() 诱导WebDriverWait,您可以使用以下Locator Strategies 之一:

    • 使用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"))
      
    • 使用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"))
      
    • 注意:您必须添加以下导入:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-09
      • 2021-02-12
      相关资源
      最近更新 更多