python selenium 自动下载文档

关于urllib2这个模块,用的时候出错,后来百度了,发现这是python2的模块,python3 中将其改为urllib.request和urllib.error两个模块。使用这两个也能够完成get, open等功能。但是还是直接用python3中的requests模块比较简单,下面网站是关于此模块的一个总结。
http://docs.python-requests.org/zh_CN/latest/user/quickstart.html
看了几个通过爬虫下载文档的例子,但是但是这些需要下载文档的链接是可以获取的。而要爬的文档链接是不能通过网页内容查找到的(水平有限),点击下载按钮知识超链接自身,发现百度文库等很多文档下载类似的网站都是这样的。
在网上找了一个爬酷狗音乐下载音乐的例子,复制其程序运行后,出现报错。
Service chromedriver unexpectedly exited
解决方法:下载chromedriver.exe,
下载链接:http://chromedriver.storage.googleapis.com/index.html
打开你的chrome 浏览器点击帮助在点击关于Googel Chrome,即可看到你浏览器的版本,然后在上面链接中找到对应于你浏览器版本的chromedriver.exe下载
下载后将Chrome.exe文件放置在python 目录下,Chrome浏览器安装目录下,当前文档目录下。其实放在当前文档的目录下就差不多了。--解决了上述问题
运行后又出现Message: Can not connect to the Service chromedriver
解决方法:把hosts(在此目录C:\Windows\System32\drivers\etc)文件里的
127.0.0.1 localhost这行注释去掉就可以。
time 模块
time.ctime()返回当前时间
time.sleep(secs)挂起时间单位秒
个人对网页程序的理解,一个标签代表一个对象。要使用函数、方法是针对整个标签而不是对标签里面的元素。在使用xpath时遇到处理中文字符,可以使用u‘查找内容’,参见博客
http://blog.csdn.net/zcc_0015/article/details/52274996
ActionChains类继承自object类,但是需要为其传入一个driver对象,即ActionChains(driver)
此类常用于模拟鼠标键盘操作。
参照博客:http://blog.csdn.net/dszgf5717/article/details/70478075
学习Selenium、Xpath等模块的学习参照下面的博客
http://www.cnblogs.com/BigFishFly/p/6380016.html
之前的思路是一直想着在html中找到文件的超链接,发现这开发者应该对其做了隐藏(不了解),换一个思路,自己模拟人操作电脑,去点击下载人后吧下在的文件放在指定的文件夹中。

结合pyqt5做了个简单的下载界面,将搜索出的文档文本框浏览器中。根据序号选择多个自己想下载的文档。然后点击下载即可下载到Chrome的指定下载路径中。提供了一个进度条用于提醒是否下载完成。程序还是比较简单的,就是模拟鼠标键盘操作和爬虫还有那么一定不一样。

# -*- coding: utf-8 -*-

"""
Module implementing mainWindow.
"""
#modules of systerm
import time
import sys

# modules of pyqt5

from PyQt5 import  QtWidgets  
from PyQt5.QtCore import pyqtSlot
from PyQt5.QtCore import QDate, Qt
from PyQt5.QtWidgets import QMainWindow
from Ui_mfiledownload import Ui_mainWindow
# modules of spider
from selenium.webdriver.remote.webelement import WebElement
from selenium import webdriver
from selenium.common.exceptions import StaleElementReferenceException
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys


class mainWindow(QMainWindow, Ui_mainWindow):
    """
    Class documentation goes here.
    """
    def __init__(self, parent=None):
        """
        Constructor
        
        @param parent reference to the parent widget
        @type QWidget
        """
        super(mainWindow, self).__init__(parent)
        self.setupUi(self)
        self.driver = webdriver.Chrome()
        self.date=QDate.currentDate()
        self.lcdNumber.display(self.date.toString(Qt.ISODate))
        self.progressBar.setValue(0)
        
    def log_in(self):
        """
        """
        self.driver.get("http://sx.zxxk.com/m/jc-book466/")  #open the website
        time.sleep(1)
        self.driver.find_element_by_xpath("html/body/div[2]//a[@class='login-btn']").click() #log in
        time.sleep(0.3)
        self.result_url = self.driver.current_url
        self.driver.get(self.result_url)
        #print(driver.page_source)
        self.driver.find_element_by_id("username").send_keys("********")
        time.sleep(0.5)
        self.driver.find_element_by_name("password").send_keys("*********")
        time.sleep(0.5)
        self.driver.find_element_by_id("CommonLogin").click()
        time.sleep(0.5)
        self.driver.find_element_by_xpath(u"//a[@title='免费']").click()
        self.label.setText("登录成功")
        
        
    def search(self):
        """
        """
        self.driver.find_element_by_xpath(u"//input[@id='SearchKey']").send_keys(self.textEdit.toPlainText())  #search
        self.driver.find_element_by_id("SearchButton").click()
        self.currenturl=self.driver.current_url
        time.sleep(1)
        for i in range(1,100):
            try:
                self.textBrowser.insertPlainText('%d. '%i + self.driver.find_element_by_xpath(".//*[@class='list-cont']/div[%d]/div[1]/div/a"%i).get_attribute('title')+'\n')   #display the results
            except NoSuchElementException as msg:
                break

    def download(self):
        """
        """
        def wait(driver):
            elem = driver.find_element_by_tag_name('html')
            count = 0
            while True:
                count += 1
                if count > 20:
                    print('chao shi le')
                    return
                time.sleep(.5)
                try:
                    elem == driver.find_element_by_tag_name('html')
                except StaleElementReferenceException:
                    return
        self.list_num=self.textEdit_2.toPlainText().split(' ')
        j=0
        for i in self.list_num:
            j+=1
            self.a = self.driver.find_element_by_xpath(".//*[@class='list-cont']/div[%d]/div[1]/div/a"%int(i))
            self.actions = ActionChains(self.driver)
            self.actions.move_to_element(self.a)
            self.actions.click(self.a)
            self.actions.perform()
            wait(self.driver)
            self.driver.switch_to_window(self.driver.window_handles[j])  
            time.sleep(1)
            self.driver.find_element_by_xpath(".//*[@id='btnSoftDownload']/div").click()
            time.sleep(2)
            self.driver.get(self.currenturl)
            time.sleep(2)
            self.progressBar.setValue(int(j*100/len(self.list_num)))
            time.sleep(0.1)
           

        
if __name__ == "__main__":  
    app = QtWidgets.QApplication(sys.argv)  
    mygui = mainWindow()  # set a GUI object to show it   
    mygui.show()  
    sys.exit(app.exec_())  
运行中无法去掉因为调用Chromedrive 出现的黑框控制台

在打包py程序生成exe在-F 加-w即可去掉运行exe文件所带的控制台

python selenium 自动下载文档_第1张图片






你可能感兴趣的:(python selenium 自动下载文档)