【问题标题】:How to get href from h3 Selenium/Python?如何从 h3 Selenium/Python 获取 href?
【发布时间】:2020-04-16 20:24:07
【问题描述】:

网址:https://www.piie.com/research/economic-issues/coronavirus

我正在尝试从“字段字段--标题”类中提取 href,但我的编码不起作用

driver.get('https://www.piie.com/research/economic-issues/coronavirus')

for i in driver.find_elements_by_class_name('field field--title'):
    for a in i.find_elements_by_css_selector('a'):
        print(a.get_attribute('href'))
        print(a.text)

HTML 如下所示:

谁能帮我解决这个问题?谢谢

【问题讨论】:

    标签: python-3.x selenium-webdriver web-scraping


    【解决方案1】:

    您应该等待元素出现在网页中,然后再尝试从它们中获取内容。因为 Selenium 有隐式和显式等待解决方案。您可以找到关于等待herehere 的非常好的信息。

    在下面的代码中,我使用显式等待元素可见以便能够从中获取文本。

    from selenium import webdriver
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    
    with webdriver.Chrome() as driver:
        wait = WebDriverWait(driver, 10)
    
        driver.get('https://www.piie.com/research/economic-issues/coronavirus')
    
        items = wait.until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, '.field--title a')))
        for item in items:
            print(item.text, item.get_attribute('href'))
    

    【讨论】:

    • 谢谢!我想知道使用 Selenium 解析 URL 时是否总是需要 wait.until()?
    • 我用它99.99%
    • 谢谢!最后一个问题,显式等待是否比隐式等待更好?或者使用没有区别。
    • 更有用
    猜你喜欢
    • 1970-01-01
    • 2023-03-29
    • 2018-05-12
    • 1970-01-01
    • 2022-01-05
    • 1970-01-01
    • 2019-01-09
    • 2021-07-30
    • 1970-01-01
    相关资源
    最近更新 更多