如何点击带有PDF内容的第一个链接

2024-09-29 23:22:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我对selenium和python还不熟悉,我想获得pdf。所以我试过了

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)

但这不会点击链接。pdf元素的范围是“跨度.sFZIhb.b.w.xsm“它标识但不单击链接。任何感谢帮助


Tags: pathurlpdf链接macdownloadsdriverselenium
2条回答

基于@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)

欢迎来到selenium有很多乐趣等着你!在

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

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

相关问题 更多 >

    热门问题