天天看點

python擷取的網頁的js_Web-用Python抓取JavaScript頁面

在普通的蜘蛛中,您可以使用請求對象來打開URL。如果要打開的頁面包含JS生成的資料,則必須使用SplashRequest(或SplashFormRequest)來呈現頁面。下面是一個簡單的例子:class MySpider(scrapy.Spider):

name = "jsscraper"

start_urls = ["http://quotes.toscrape.com/js/"]

def start_requests(self):

for url in self.start_urls:

yield SplashRequest(

url=url, callback=self.parse, endpoint='render.html'

)

def parse(self, response):

for q in response.css("div.quote"):

quote = QuoteItem()

quote["author"] = q.css(".author::text").extract_first()

quote["quote"] = q.css(".text::text").extract_first()

yield quote

SplashRequest将URL呈現為html,并傳回您可以在回調(解析)方法中使用的響應。