Python 如何使Scrapy仅爬行1页(使其非递归)?
我正在使用scrapy()的最新版本,并试图找出如何使scrapy只抓取作为start_URL列表的一部分提供给它的URL。在大多数情况下,我只想抓取一个页面,但在某些情况下,我可能会指定多个页面。我不想让它爬到其他页面 我已经尝试将深度级别设置为1,但我不确定在测试中它是否实现了我希望实现的目标 任何帮助都将不胜感激 谢谢大家! 2015年12月22日-代码更新:Python 如何使Scrapy仅爬行1页(使其非递归)?,python,scrapy,Python,Scrapy,我正在使用scrapy()的最新版本,并试图找出如何使scrapy只抓取作为start_URL列表的一部分提供给它的URL。在大多数情况下,我只想抓取一个页面,但在某些情况下,我可能会指定多个页面。我不想让它爬到其他页面 我已经尝试将深度级别设置为1,但我不确定在测试中它是否实现了我希望实现的目标 任何帮助都将不胜感激 谢谢大家! 2015年12月22日-代码更新: # -*- coding: utf-8 -*- import scrapy from generic.items import G
# -*- coding: utf-8 -*-
import scrapy
from generic.items import GenericItem
class GenericspiderSpider(scrapy.Spider):
name = "genericspider"
def __init__(self, domain, start_url, entity_id):
self.allowed_domains = [domain]
self.start_urls = [start_url]
self.entity_id = entity_id
def parse(self, response):
for href in response.css("a::attr('href')"):
url = response.urljoin(href.extract())
yield scrapy.Request(url, callback=self.parse_dir_contents)
def parse_dir_contents(self, response):
for sel in response.xpath("//body//a"):
item = GenericItem()
item['entity_id'] = self.entity_id
# gets the actual email address
item['emails'] = response.xpath("//a[starts-with(@href, 'mailto')]").re(r'mailto:\s*(.*?)"')
yield item
下面,在第一个回答中,您提到使用一个通用的spider——这不是我在代码中所做的吗?你还建议我删除
callback=self.parse_dir_contents
从解析函数
多谢各位 看起来您正在使用
爬行爬行器
,这是一种特殊的爬行器
来爬行页面内的多个类别
仅对
start\u url
中指定的URL进行爬网,只需覆盖parse
方法,因为这是启动请求的默认回调。下面是爬行器的代码,爬行器将从博客中刮取标题(注意:xpath可能不适用于每个博客)
文件名:/spider/my_spider.py
class MySpider(scrapy.Spider):
name = "craig"
allowed_domains = ["www.blogtrepreneur.com"]
start_urls = ["http://www.blogtrepreneur.com/the-best-juice-cleanse-for-weight-loss/"]
def parse(self, response):
hxs = HtmlXPathSelector(response)
dive = response.xpath('//div[@id="tve_editor"]')
items = []
item = DmozItem()
item["title"] = response.xpath('//h1/text()').extract()
item["article"] = response.xpath('//div[@id="tve_editor"]//p//text()').extract()
items.append(item)
return items
上面的代码将只获取给定文章的标题和文章正文。感谢您的提示,我在文章中添加了一个代码示例和一个问题,以进一步澄清。顺便说一句,节日快乐!