[英]File downloading using splash with button click
我有一個蜘蛛用來抓取一些數據和一個 pdf 文件。 除了pdf,一切都完成了。 pdf 沒有直接的 src 可以下載到 file_urls 字段。 html看起來像這樣
<a onclick="document.forms[0].target ='_blank';" id="main_0_body_0_lnkDownloadBio" href="javascript:__doPostBack('main_0$body_0$lnkDownloadBio','')">Download full <span class="no-wrap">bio <i class="fa fa-angle-right" data-nowrap-cta=""></i></span></a>
似乎一些 javascript click 方法正在工作,而不是 src。 當我們點擊這個時,它將打開一個新窗口,其中包含下載選項。 現在我計划將啟動請求與 lua 腳本一起使用。 這是代碼
class DataSpider(scrapy.Spider):
name = config.NAME
allowed_domains = [config.DOMAIN]
def start_requests(self):
for url in config.START_URLS:
yield scrapy.Request(url, self.parse_data)
def parse_data(self, response):
script = """
function main(splash)
local url = splash.args.url
assert(splash:go(url))
assert(splash:wait(1))
-- go back 1 month in time and wait a little (1 second)
assert(splash:runjs("document.getElementById('DownloadBio').click()"))
assert(splash:wait(1))
-- return result as a JSON object
return {
html = splash:html(),
}
end
"""
response = json.loads(response.text)
res = response['people']
for index, i in enumerate(res[1]):
first_name = res[index]['name']
last_name = res[index]['lastname']
location = res[index]['location']
link = res[index]['pageurl']
link = config.HOST + link
item = ProtoscraperItem(first_name=first_name, last_name=last_name, title=title, location=location, link=link)
# This request is for the detail page and there is more info and pdf.
request = SplashRequest(link, self.parse_details, meta={
'splash': {
'args': {'lua_source': script, 'wait': 30, 'timeout': 40},
'endpoint': 'execute',
},)
request.meta['item'] = item
request.meta['link'] = link
yield request
def parse_details(self, response):
# what to do here
所以在這里我單擊錨標記來執行 javscript。 我認為它正在運行,但沒有下載任何內容。 我在這里缺少什么。 可以指定下載路徑嗎? 我認為這可以用 selenium 實現,但我怎么能用飛濺和 lua 做到這一點?
通過查看單擊按鈕,我相信它正在調用 ASP.net 中的“__doPostBack”函數。 當您單擊該提交按鈕時,表單 [0] 將與某些值一起提交。 您需要為通過表單提交提交的所有元素檢查頁面。
這樣做所需的參數是
__事件目標,
__事件參數
__視圖狀態
__視圖狀態生成器
__事件驗證
也許更多,通常這些參數被設置為表單中的隱藏值。 (請在您的網頁中進行驗證)
arguments = {'__EVENTTARGET': 'main_0$body_0$lnkDownloadBio',
'__EVENTARGUMENT': '',
'__VIEWSTATE': viewstate,
'__VIEWSTATEGENERATOR': viewstategen,
'__EVENTVALIDATION': eventvalid,
'search': '',
'filters': '',
'score': ''
}
HEADERS = {
'Content-Type':'application/x-www-form-urlencoded',
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64)
AppleWebKit/537.36 (KHTML, like Gecko)
Chrome/60.0.3112.101 Safari/537.36',
'Accept': 'text / html, application / xhtml + xml,
application / xml;q = 0.9, image / webp, image / apng, *
/ *;q = 0.8'
}
data = urllib.urlencode(arguments)
r = requests.post(submitin_url, data, allow_redirects=False, headers=HEADERS)
with open(some_filename, 'wb') as f:
f.write(r.content)
我的項目有類似的工作,我已經這樣做了。 使用 Python 請求發送表單值和參數。 響應將是您嘗試下載的文件。 將其寫入文件並確保擴展名正確。 我希望它會對你有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.