使用Selenium下载链接文件

时间:2017-11-09 18:03:03

标签: python selenium

我是selenium的新手,我正试图用它来提取一些数据。基本上,我的目标是使用外部下载工具自动下载SoundCloud上的曲目。我的目标是浏览网站,然后右键单击最后一页上的按钮并选择“下载链接文件”。这是我的代码:

from selenium import webdriver
from time import sleep
from selenium.webdriver import ActionChains

def gettrackfeatures(track):
    browser = webdriver.Safari()
    browser.get('https://scdownloader.net')
    print("Starting Page:", browser.current_url)
    maininput = browser.find_element_by_id('songURL')

    maininput.send_keys(track)

    button = browser.find_element_by_css_selector('button.secondary')
    button.click()
    sleep(5)
    print("One Click:", browser.current_url)

    button = browser.find_element_by_xpath('''//*[@id="results-wrapper"]/a''')
    ActionChains.context_click(button).perform()
    sleep(5)
    print("Two Clicks:", browser.current_url)

    browser.quit()

gettrackfeatures("https://soundcloud.com/rickyxsan/1nsane")

我发现其他一些问题导致我尝试动作链,但我不断收到此错误:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-23-acee249e870f> in <module>()
     33 
     34 
---> 35 gettrackfeatures("https://soundcloud.com/rickyxsan/1nsane")

<ipython-input-23-acee249e870f> in gettrackfeatures(track)
     24 
     25     button = browser.find_element_by_xpath('''//*[@id="results-wrapper"]/a''')
---> 26     ActionChains.context_click(button).perform()
     27     sleep(5)
     28     print("Two Clicks:", browser.current_url)

//anaconda/lib/python3.5/site-packages/selenium/webdriver/common/action_chains.py in context_click(self, on_element)
    136            If None, clicks on current mouse position.
    137         """
--> 138         if self._driver.w3c:
    139             self.w3c_actions.pointer_action.context_click(on_element)
    140             self.w3c_actions.key_action.pause()

AttributeError: 'WebElement' object has no attribute '_driver'

2 个答案:

答案 0 :(得分:0)

你几乎就在那里,在你获得带有xpath //*[@id="results-wrapper"]/a的元素后,你可以简单地调用.click

建议:不要使用sleep(5),请务必使用explicit waits

Here包含您可以使用的所有预期条件的链接。

整个代码:

driver.get("https://scdownloader.net")
track="https://soundcloud.com/rickyxsan/1nsane"

maininput = driver.find_element_by_id('songURL')
maininput.send_keys(track)
button = driver.find_element_by_css_selector('button.secondary')
button.click()

wait = WebDriverWait(driver, 20)
downloadButton= wait.until(EC.element_to_be_clickable((By.XPATH,"//*[@id='results-wrapper']/a")))
downloadButton.click()

答案 1 :(得分:0)

而不是:

ActionChains.context_click(button).perform()

尝试使用:

from selenium.webdriver import ActionChains
#your other lines of code
actions = ActionChains(browser)
actions.context_click(button).perform()