如何为monster.com创建抓取工具以抓取所有网页。对于“下一页”链接,monster.com调用javascript函数但scrapy无法识别javascript
这是我的代码,它不适用于分页:
import scrapy
class MonsterComSpider(scrapy.Spider):
name = 'monster.com'
allowed_domains = ['www.monsterindia.com']
start_urls = ['http://www.monsterindia.com/data-analyst-jobs.html/']
def parse(self, response):
urls = response.css('h2.seotitle > a::attr(href)').extract()
for url in urls:
yield scrapy.Request(url =url, callback = self.parse_details)
#crawling all the pages
next_page_url = response.css('ul.pager > li > a::attr(althref)').extract()
if next_page_url:
next_page_url = response.urljoin(next_page_url)
yield scrapy.Request(url = next_page_url, callback = self.parse)
def parse_details(self,response):
yield {
'name' : response.css('h3 > a > span::text').extract()
}
答案 0 :(得分:1)
您的代码会抛出异常,因为next_page_url
是list
,而response.urljoin
方法需要一个字符串。下一页链接提取应如下所示:
next_page_url = response.css('ul.pager > li > a::attr(althref)').extract_first()
(即用extract()
替换extract_first()
)
修改强>
next_page_url
提取还有另一个问题。所有逻辑都是正确的并且分页有效,但是下一页链接仅适用于第一页。首先需要a
,但在第二页上还有上一页页面链接。将下一页网址提取修改为:
next_page_url = response.css('ul.pager').xpath('//a[contains(text(), "Next")]/@althref').extract_first()
现在它正确分页到所有页面。