【问题标题】:Scrapy not returning results in for specific tagsScrapy不返回特定标签的结果
【发布时间】:2019-01-15 17:35:35
【问题描述】:

我今天刚开始使用Scrapy,但是我之前有过javascript的编程经验,所以请多多包涵,我会给出非常详细的解释:

我正在使用 gramReport 分析一些 instagram 个人资料(提取关注者数量、帖子数量和其他数据。),因为我有一个不同个人资料的列表,我想自动执行此任务;

最终的想法是这样的:

1. Use Scrapy to crawl a specific profile ( so append 'profile' to 'gramreport.com/user/' )
2. Extract specific data and save it in a csv

我认为 python 可以完成这项工作,开始搜索并找到了 scrapy ,文档对我来说是完美的。 https://doc.scrapy.org/en/latest/intro/tutorial.html

我决定像教程一样尝试一下,我创建了一个蜘蛛:

import scrapy
class QuotesSpider(scrapy.Spider):
name = "profile"
start_urls = [
    'http://gramreport.com/user/cats.gato'
]

def parse(self, response):
    page = response.url.split("/")[-1]
    filename = 'profile-%s.html' % page
    with open(filename, 'wb') as f:
        f.write(response.body)

所以scrapy crawl profile 完美运行我无法获取 html 页面。 接下来我尝试使用外壳:

scrapy shell 'http://gramreport.com/user/cats.gato'

太好了,我可以通过 Xpath 或 CSS 获取一些数据:

//Followers:
response.xpath('/html/body/div[3]/table[1]/tr/td[2]/table/tr[1]/td/div/table/tr[2]/td/text()').extract()

//Posts:
response.xpath('/html/body/div[3]/table[1]/tr/td[2]/table/tr[3]/td/div/table/tr[2]/td/text()').extract()

//Page Name:
response.xpath('/html/body/div[3]/table[1]/tr/td[1]/div/div/div/span[2]/text()').extract()

//Average Likes:
response.xpath('/html/body/div[3]/div[1]/div/div/div[1]/div/text()').extract()

//Average Comments:
response.xpath('/html/body/div[3]/div[1]/div/div/div[2]/div/text()').extract()

我得到的大多数结果都有 u' 字符和其他正则表达式,例如 [u'\n\t\t\t252,124\t\t'],但我认为已经有回复的帖子。

但是,有些数据我无法提取,我根本没有得到任何结果;

首先是Recent Interactions 表,这是因为 AJAX 发生的,但我就是不明白如何修复它;也许使用延迟?

第二个Top HashtagsTop User Mentions 表;

他们的 Xpath 不起作用,css 选择器也不起作用;我不知道为什么。

【问题讨论】:

    标签: python xpath web-scraping scrapy web-crawler


    【解决方案1】:

    页面加载时会发出 AJAX 请求。

    如果您在加载页面时打开网络检查器,您将看到如下 AJAX 请求:

    如果你 ctrl+f 在页面源中这个请求中使用的一些 id,你会看到一些类似的 javascript:

    你可以使用scrapy找到这个url,然后转发请求:

    def parse(self, response):
    
        script = response.xpath("//script[contains(text(), 'getresultsb']")
        url = script.re('url:"(.+?)"')  # capture between ""
        headers = {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            'X-Requested-With': 'XMLHttpRequest',
        }
        yield Request(url, 
            method='POST', 
            body='dmn=ok', 
            callback=self.parse_recent
            headers=headers,
        )
    
    def parse_recent(self, response):
        # parse recent data here
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-13
      • 2018-01-21
      • 1970-01-01
      • 2021-05-01
      • 2019-07-09
      • 1970-01-01
      相关资源
      最近更新 更多