使用Scrapy模拟JavaScript按钮点击
问题描述:
我的意图是在此网页上运行scrapy抓取工具:http://visit.rio/en/o-que-fazer/outdoors/。但是,id =“container”上的某些资源只能通过JavaScript按钮(“VER MAIS”)进行加载。我读过一些关于硒的东西,但我什么都没有。使用Scrapy模拟JavaScript按钮点击
答
您的阅读正确无误,您最好的选择是使用Firefox浏览器或无头像PhantomJS的scrapy + selenium,以加快抓取速度。改编自https://stackoverflow.com/a/17979285/2781701
import scrapy
from selenium import webdriver
class ProductSpider(scrapy.Spider):
name = "product_spider"
allowed_domains = ['visit.rio']
start_urls = ['http://visit.rio/en/o-que-fazer/outdoors']
def __init__(self):
self.driver = webdriver.Firefox()
def parse(self, response):
self.driver.get(response.url)
while True:
next = self.driver.find_element_by_xpath('//div[@id="show_more"]/a')
try:
next.click()
# get the data and write it to scrapy items
except:
break
self.driver.close()
实施例