xpath为什么我在这个expth中得到空结果

时间:2015-03-02 12:41:38

标签: python xpath web-scraping scrapy

我试试这个xpath

.//div[@class='owl-wrapper']

在这个网站上

http://www.justproperty.com/search/uae/apartments/filter__cid/0/sort/score__desc/per_page/20/page/1

但我得到了空洞的结果,不过我可以在Google F12开发者工具中看到它。

你可能认为这是一个javascript调用,但不是因为,我正在使用scrapy而且我可以view这样的回复:

scrapy shell ("website")
view(response)

那个班级在那里。

请帮助

我的Chrome屏幕截图,其中包含使用视图(响应)

的页面

Screenshot from my Chrome for the page that comes using view(response)

1 个答案:

答案 0 :(得分:3)

问题是:包含带divowl-wrapper元素的搜索结果与其他GET请求异步加载。

您需要在代码中模拟此请求,例如使用requests

import requests

with requests.Session() as session:
    session.get('http://www.justproperty.com/search/uae/apartments/filter__cid/0/sort/score__desc/per_page/20/page/1')

    params = {
        'url': 'filter__cid/0/sort/score__desc/per_page/20/page/1',
        'ajax': 'true'
    }
    response = session.get('http://www.justproperty.com/search/featured-properties/', params=params)
    results = response.json()

    for result in results:
        print result['description']

打印:

2 bedroom unit on high floor. Full Fountain View,It comes with different amenities, facilities and hotel services. It is located in a prime location, The Address Hotel Lake Downtown. This property is...
Large Upgraded 1 Bedroom For Sale In Index Tower DIFC With DIFC ViewSize: 840 square feet - 78 square metersBedroom: 1 Bathroom: 1 plus guest washroomKitchen: Fully Equipped modern style kitchen with...
Spacious and nice 1-bedroom apartment for
...

示例Scrapy蜘蛛基于上面提供的解决方案:

import json

import scrapy


class JustPropertySpider(scrapy.Spider):
    name = "justproperty"
    allowed_domains = ["justproperty.com"]
    start_urls = [
        "http://www.justproperty.com/search/uae/apartments/filter__cid/0/sort/score__desc/per_page/20/page/1"
    ]

    def parse(self, response):
        yield scrapy.Request('http://www.justproperty.com/search/featured-properties/?url=filter__cid/0/sort/score__desc/per_page/20/page/1&ajax=true',
                             callback=self.parse_results,
                             headers={'X-Requested-With': 'XMLHttpRequest'})

    def parse_results(self, response):
        results = json.loads(response.body)

        for result in results:
            print result['description']