我刚开始爬行。我试图通过使用Scrapy框架和Python 2.7下载内容来抓取网站http://www.indiabix.com/verbal-ability/spotting-errors/中的问题和答案。我注意到,如果你查看它的来源,你会注意到每个问题的答案应该在b标签中,但不是:
<div class="div-spacer">
<p><span class="ib-green"><b>Answer:</b></span> Option <b class="jq-hdnakqb"></b></p>
<p><span class="ib-green"><b>Explanation:</b></span></p>
<p> No answer description available for this question. <b><a href="discussion-399">Let us discuss</a></b>. </p>
如果我们检查网页上的元素,我们可以在标签之间看到正确的答案:答案:每个问题的选项A或B等,但HTML源代码不是。
要获取b标记内的文本,我使用xpath尝试了大约15个查询。 我在下面的代码中写了最可能的4-5个查询作为注释。
import scrapy
import urllib
import json
from errors1.items import Errors1Item
class Errors1Spider(scrapy.Spider) :
name = "errors1"
start_urls = ["http://www.indiabix.com/verbal-ability/spotting-errors/"]
def parse(self, response) :
i = 0
y = 0
j = json.loads(json.dumps(response.xpath('//td[contains(@id, "tdOption")]/text()').extract()))
x = json.loads(json.dumps(response.xpath('//div[@class="div-spacer"]/p[3]/text()').extract()))
#to get correct answer
#response.xpath('//div[@class = "div-spacer"]/p/b/text()').extract()
#response.xpath('//div[@class = "div-spacer"]/p[1]/b/text()').extract()
#response.xpath('//div[@class = "div-spacer"]/p//text()').extract()
#response.xpath('//b[@class = "jq-hdnakqb"]/text()').extract()
#response.xpath('string(//div[@class = "div-spacer"]/p/b/text())').extract()
while i<len(j) and y<len(x) :
item = Errors1Item()
item['optionA'] = j[i]
i+=1
item['optionB'] = j[i]
i+=1
item['optionC'] = j[i]
i+=1
item['optionD'] = j[i]
i+=1
item['explanation'] = x[y]
y+=1
yield item
有人可以帮我从该网页获取答案内容。 感谢
答案 0 :(得分:1)
据我所知,设置正确的选项值涉及到javascript逻辑。
帮助我解决问题的是scrapyjs
middleware,它使用Splash
浏览器即服务。跳过安装和配置,这是我执行的蜘蛛:
# -*- coding: utf-8 -*-
import scrapy
class IndiaBixSpider(scrapy.Spider):
name = "indiabix"
allowed_domain = ["www.indiabix.com"]
start_urls = ["http://www.indiabix.com/verbal-ability/spotting-errors/"]
def start_requests(self):
for url in self.start_urls:
yield scrapy.Request(url, meta={
'splash': {
'endpoint': 'render.html',
'args': {'wait': 0.5}
}
})
def parse(self, response):
for question in response.css("div.bix-div-container"):
answer = question.xpath(".//input[starts-with(@id, 'hdnAnswer')]/@value").extract()
print answer
以下是我在控制台上获得的内容(正确答案):
[u'A']
[u'C']
[u'A']
[u'C']
[u'C']
[u'C']
[u'B']
[u'A']
[u'D']
[u'C']
[u'B']
[u'B']
[u'A']
[u'B']
[u'B']
另见: