網絡抓取的時候會碰到需要從網站下載文件的情況。下面提供兩種方法:
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