我有一個蜘蛛用於刮一些數據以及pdf文件。一切都完成,除了pdf。 pdf沒有直接下載到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點擊方法工作,而不是SRC。當我們點擊這個,它會打開一個新的窗口,下載選項。現在我計劃使用splash請求和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。我認爲它正在工作,但沒有下載。我在這裏錯過了什麼。是否可以指定要下載的路徑?我認爲這可能與硒,但我怎麼能做到這一點與飛濺和盧阿?
'parse_details'方法中的response.body是什麼? –
我剛剛在另一個網站上下載了PDF格式的文件,它似乎不適合你。因此,您需要做的是查看在正常瀏覽器中提交表單時啓動的請求類型,並嘗試通過普通瀏覽器直接模擬請求 –
@TarunLalwani表單提交發起請求並使用pdf打開新選項卡。這是在下載或打印任何文檔之前的瀏覽器預覽。 我已經從代碼提交了相同的表單,但是我收到了與響應文本相同的html。你能告訴我如何發送這個請求和過程? –