Scrapy + Splash + ScrapyJS

﹥>﹥吖頭↗ 提交于 2019-12-04 08:37:30

You can avoid having to use Splash in the first place and make the appropriate GET request to get the phone number yourself. Working spider:

import json
import re

import scrapy   

class OlxSpider(scrapy.Spider):
    name = "olx"
    rotate_user_agent = True
    allowed_domains = ["olx.pt"]
    start_urls = [
        "https://olx.pt/imoveis/"
    ]

    def parse(self, response):
        for href in response.css('.link.linkWithHash.detailsLink::attr(href)'):
            url = response.urljoin(href.extract())
            yield scrapy.Request(url, callback=self.parse_house_contents)

        for next_page in response.css('.pager .br3.brc8::attr(href)'):
            url = response.urljoin(next_page.extract())
            yield scrapy.Request(url, self.parse)

    def parse_house_contents(self, response):
        property_id = re.search(r"ID(\w+)\.", response.url).group(1)

        phone_url = "https://olx.pt/ajax/misc/contact/phone/%s/" % property_id
        yield scrapy.Request(phone_url, callback=self.parse_phone)

    def parse_phone(self, response):
        phone_number = json.loads(response.body)["value"]
        print(phone_number)

If there are more things to extract from this "dynamic" website, see if Splash is really enough and, if not, look into browser automation and selenium.

Add

splash:autoload("https://code.jquery.com/jquery-2.1.3.min.js")

to Lua script and it will work.

function main(splash)
    splash:go(splash.args.url)
    splash:autoload("https://code.jquery.com/jquery-2.1.3.min.js")
    splash:runjs('document.getElementById("contact_methods").getElementsByTagName("span")[1].click();')
    splash:wait(0.5)
    return splash:html()
end

.click() is JQuery function https://api.jquery.com/click/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!