我今天刚开始使用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页面。接下来,我尝试使用shell:
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 Hashtags
和Top User Mentions
表;
它们的Xpath不起作用,css选择器也不起作用;我不知道为什么。
发布于 2019-01-16 06:24:06
当页面加载时,会发出一个AJAX请求。
如果你在加载页面时打开网页检查器,你会看到如下的AJAX请求:
如果你在页面源代码中ctrl+f这个请求中使用的一些ids,你会看到一些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
https://stackoverflow.com/questions/54204121
复制相似问题