您的位置:首页 > 编程语言 > Python开发

爬虫之自动保存文档-使用python/selenium

2015-11-27 17:01 881 查看
网络抓取的时候会碰到需要从网站下载文件的情况。下面提供两种方法:

 1.  selenium + firefox + firefoxProfile

核心要点是在firefox中设置相关的下载参数,然后在模拟点击的时候,selenium webdriver会自动保存对应的文档。

貌似文件的自动保存需要使用的webdriver只能是firefox。在网上并没有搜到使用对其他webdriver工具的支持资料。

selenium的自动存档可以参考《Docs-Selenium Python Bindings》(github上的一个python-selenium的使用文档,很靠谱)中的常见问题How
to auto save files using custom Firefox profile

prof = webdriver.FirefoxProfile();
# 下面几个是核心参数
prof.set_preference("browser.download.folderList", 2) # 2表示自定义文件夹 0表示保存到桌面
prof.set_preference("browser.download.manager.showWhenStarting",False) # 没什么用
prof.set_preference("browser.download.dir","D:\\selenium\\") # 设置默认的保存文件夹
# 设置自动保存的文件类型,如果firefox不能自动保存,一定是文件类型不对</span>
prof.set_preference("browser.helperApps.neverAsk.saveToDisk", 'application/a-gzip,application/x-gzip')
# 其他可选文件类型"application/x-gzip;application/zip,application/x-gtar,text/plain,application/x-compressed,application/octet-stream,application/pdf")
# 下面这些参数是从别的地方看到的
prof.set_preference("browser.helperApps.alwaysAsk.force", False)
prof.set_preference("browser.download.manager.alertOnEXEOpen", False)
prof.set_preference("browser.download.manager.focusWhenStarting", False)
prof.set_preference("browser.download.useDownloadDir", True)
prof.set_preference("browser.download.manager.alertOnEXEOpen", False)
prof.set_preference("browser.download.manager.closeWhenDone", True)
prof.set_preference("browser.download.manager.showAlertOnComplete", False)
prof.set_preference("browser.download.manager.useWindow", False) #
#disable Firefox's built-in PDF viewer
prof.set_preference("pdfjs.disabled",True)

# 给firefox使用 driver = webdriver.Firefox(firefox_profile=prof)
# 直接点击下载按钮,文件就会自动保存了
driver.get(url)
driver.find_element_by_css_selector(".primary-").click()

文件的MIME类型可以参考wiki《List of archive formats

2. urllib2直接保存

使用urllib2直接读取请求的url,urllib2可以保存网页返回的结果,直接写文件就可以达到保存的目的

 try:
    url = 'https://reportingitc2.apple.com/api/report?vendorID=85865236&reportType=2A&endDate=2015%2F11%2F24&vendorType=1&CSRF=' + self.header_csrf
    print url #待访问的url
    request = urllib2.Request(url)
#             request.add_header('Accept-encoding', '"gzip, deflate')
    request.add_header('Cookie', self.cookie_header) #添加cookie
    request.add_header('User-Agent','Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.155 Safari/537.36')
#             request.add_header('Host', 'itunesconnect.apple.com')
    try:
        pageText = urllib2.urlopen(request, timeout=30).read()
        open('D:/selenium/b.txt.gz', "wb").write(pageText) #保存返回的下载文件,如果是压缩文件,使用wb,而不是w
        print "[succ]download gz_file successfully."
    except urllib2.URLError, e:
        print e    
except urllib2.URLError, e:
    print e
 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  selenium 爬虫 urllib2