【问题标题】:Value being returned by Selenium get_attribute() is always 1Selenium get_attribute() 返回的值始终为 1
【发布时间】:2021-09-04 18:58:05
【问题描述】:

我正在做一些业余网络抓取,但在通过 xpath 获取值时遇到了问题。我的目标是https://kek.tools/t/0x4e15361fd6b4bb609fa63c81a2be19d873717870。我的代码如下:

def scrape_price():
    options = Options()
    options.headless = True
    options.add_argument("--window-size=1920,1200")
    driver = webdriver.Chrome(options=options, executable_path=DRIVER_PATH)
    driver.get('https://kek.tools/t/0x841fad6eae12c286d1fd18d1d525dffa75c7effe')
    driver.implicitly_wait(100)
    price = driver.find_element_by_xpath('//input[@class="sc-ciSkZP sc-bjHqKj bwSYJA dbQnLk" and @tabindex="2"]')
    print(price.get_attribute("value"))
    driver.quit()

//input[@class="sc-ciSkZP sc-bjHqKj bwSYJA dbQnLk" and @tabindex="2"] 的检查元素过滤似乎得到了我需要的确切输入字段,但是当我打印值时总是返回“1”。我没有为WebElement 使用正确的方法吗?

【问题讨论】:

    标签: python selenium web-scraping xpath getattribute


    【解决方案1】:

    尝试使用expected_conditions 而不是implicitly_wait,如下所示:

    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    def scrape_price():
        options = Options()
        options.headless = True
        options.add_argument("--window-size=1920,1200")
        driver = webdriver.Chrome(options=options, executable_path=DRIVER_PATH)
        wait = WebDriverWait(driver, 20)
        driver.get('https://kek.tools/t/0x841fad6eae12c286d1fd18d1d525dffa75c7effe')
        price = wait.until(EC.visibility_of_element_located((By.XPATH, '//input[@class="sc-ciSkZP sc-bjHqKj bwSYJA dbQnLk" and @tabindex="2"]')))
        print(price.get_attribute("value"))
        driver.quit()
    

    【讨论】:

    • 哇,真快。谢谢!我很困惑,因为我认为它出于某种原因正在获取taxindex=1EC 是我绝对想要的,但我想不出合适的词来搜索它。再次感谢您。
    • expected_conditionsimplicitly_wait 上总是更可取,因为implicitly_wait 正在等待元素存在(虽然它没有最终呈现),而expected_conditions 可能等待元素可见性和可点击性 - 更成熟元素状态。
    猜你喜欢
    • 2020-09-29
    • 1970-01-01
    • 2017-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多