代码之家  ›  专栏  ›  技术社区  ›  Ricky

如何单击pdf内容的第一个链接

  •  1
  • Ricky  · 技术社区  · 6 年前

    我对selenium和python还不熟悉,我想用pdf获取第一个链接的url

    driver = webdriver.Chrome(executable_path='/Users/mac/Downloads/chromedriver')
    driver.get("https://google.com/search?query=" + searchList[i])
    driver.find_element_by_css_selector("span.sFZIhb.b.w.xsm").click()
    url = driver.current_url
    print(url)
    

    2 回复  |  直到 6 年前
        1
  •  1
  •   Moshe Slavin    6 年前

    基于@InfernO的XPath,这里有一个snip,它获取所有URL并单击第一个:

    from selenium import webdriver
    from selenium.webdriver.chrome.options import Options
    
    options = Options()
    # options.add_argument("--headless")
    options.add_argument("--incognito")
    searchList = ["pdf example", "pdf file"]
    urls = []
    for i, word in enumerate(searchList):
        driver = webdriver.Chrome("C:\workspace\TalSolutionQA\general_func_class\chromedriver.exe", chrome_options=options)
        driver.get("https://google.com/search?query=" + searchList[i])
        all_urls = driver.find_elements_by_xpath("//a[contains(@href, '.pdf')]")
        urls.append([i.get_attribute("href") for i in all_urls])
        print(f'the urls:{[i.get_attribute("href") for i in all_urls]}')
        all_urls[0].click()
        driver.quit()
    
    print(urls)
    

    欢迎来到硒很多乐趣等着你!

        2
  •  2
  •   Infern0    6 年前

    获取第一个包含url with.pdf的链接并单击它。

    driver.find_element_by_xpath("//a[contains(@href, '.pdf')])[1]").click();