单击并下载列表Selenium Python上的所有项目



我正在尝试编写一个脚本,可以下载所有日本机器每月工具订购PDF

第一步是尝试遍历每年(2010-2019(并打印所有列表项。我已经做到了。

第二部分是单击每个列表项(将下载每个pdf(。这就是我寻求帮助的地方。

enter code here
from selenium import webdriver
import time
driver = webdriver.Chrome("C:Pythonchromedriver", options=options)
driver.get("http://www.jmtba.or.jp/english/date/2019/?cat=169")
time.sleep(3)

list1 = ['2010', '2011', '2012', '2013', '2014', '2015', '2016', '2017', '2018', '2019']
i=2010
while i<=2019:
    driver.find_element_by_link_text(str(i)).click()
    # Print all Monthly Machine Tool Orders
    langs = driver.find_elements_by_css_selector("#left > ul.news_archive")
    for lang in langs:
        print(lang.text)
        lang.click()
    i = i + 1

打印每个 PDF 的所有标题,但不单击并下载它们。任何帮助非常感谢!

您正在搜索 ul 部分,因此无法单击它们。

Go to website > Right click > analyze > Drag your mouse on links

您将在跨度中看到您的链接,因此您需要搜索跨度部分。

langs = driver.find_element_by_xpath("//span[@class = 'text']//a")
langs.click()

当您像上面一样更改代码时,它将解决您的问题。如果有效,请告诉我

  1. 使用 sleep() 是某种形式的反模式,请考虑改为切换到显式等待。

    • 删除time.sleep(3)
    • 替换此行:

      driver.find_element_by_link_text(str(i)).click()
      

      有了这个:

      WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.LINK_TEXT, str(i)))).click()
      

    查看 如何使用 Selenium 使用 AJAX 技术测试 Web 应用程序 文章以获取更多详细信息

  2. 您的CSS选择器不是很正确,它应该针对a标签

    langs = driver.find_elements_by_css_selector("#left > ul.news_archive > li > span.text > a")
    
  3. 使用浏览器下载文件效率极低,我建议使用 urllib 代替:

    urllib.request.urlretrieve(lang.get_attribute('href'), lang.text + '.pdf')
    

不要使用time.sleep(3)功能,始终使用 WebDriverWait 等待特定条件发生后再继续代码。

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
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_experimental_option('prefs',  {
    "download.prompt_for_download": False,
    "download.directory_upgrade": True,
    "plugins.always_open_pdf_externally": True
    }
)
driver = webdriver.Chrome("C:Pythonchromedriver",options = chrome_options)
driver.get("http://www.jmtba.or.jp/english/date/2019/?cat=169")
i=2010
while i<=2019:
    driver.find_element_by_link_text(str(i)).click()
    WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CLASS_NAME, "news_archive")))
    results = driver.find_element_by_class_name("news_archive")
    rows = results.find_elements_by_tag_name("li")
    for row in rows:
        #  get pdf link
        a = row.find_element_by_tag_name("a")
        # download pdf
        a.click()
    i = i + 1