通过提供的建议和大量线索,我能够完成单页的抓取工作。现在,我尝试对代码进行更改,以实现多个规则,但结果看起来并不好。这是我正在尝试做的简要说明,
对于 start_url=ttp://sfbay.craigslist.org/ - 我使用 parse_items_1 来识别http://sfbay.craigslist.org/npo并解析它来识别链接
在第 2 级中,对于 ttp://sfbay.craigslist.org/npo 中的链接,我需要使用 parse_items_2 来识别http://sfbay.craigslist.org/npo/index100.html之类的链接并对其进行解析。
蜘蛛能够爬行(我可以看到显示),但链接没有被废弃。
2013-02-13 11:23:55+0530 [craigs] DEBUG: Crawled (200) <GET http://sfbay.craigslist.org/npo/index100.html> (referer: http://sfbay.craigslist.org/npo/)
('**parse_items_2:', [u'Development Associate'], [u'http://sfbay.craigslist.org/eby/npo/3610841951.html'])
('**parse_items_2:', [u'Resource Development Assistant'], [u'http://sfbay.craigslist.org/eby/npo/3610835088.html'])
但是链接和标题在报废时为空。
2013-02-13 11:23:55+0530 [craigs] DEBUG: Scraped from <200 http://sfbay.craigslist.org/npo/index100.html>
{'link': [], 'title': []}
2013-02-13 11:23:55+0530 [craigs] DEBUG: Scraped from <200 http://sfbay.craigslist.org/npo/index100.html>
{'link': [], 'title': []}
代码详情:
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import HtmlXPathSelector
from myspider.items import CraigslistSampleItem
class MySpider(CrawlSpider):
name = "craigs"
allowed_domains = ["sfbay.craigslist.org"]
start_urls = ["http://sfbay.craigslist.org/"]
rules = (
Rule(SgmlLinkExtractor(allow=("index\d00\.html")), callback="parse_items_2", follow= True),
Rule(SgmlLinkExtractor(allow=(r'sfbay.craigslist.org/npo')), callback="parse_items_1", follow= True),
)
def __init__(self, *a, **kw):
super(MySpider, self).__init__(*a, **kw)
self.items = []
self.item = CraigslistSampleItem()
def parse_items_1(self, response):
# print response.url
hxs = HtmlXPathSelector(response)
titles = hxs.select("//div")
for title in titles:
self.item ["title"] = title.select("//li/a/text()").extract()
self.item ["link"] = title.select("//li/a/@href").extract()
print ('**parse-items_1:', self.item["title"])
self.items.append(self.item)
return self.items
def parse_items_2(self, response):
# print response.url
hxs = HtmlXPathSelector(response)
titles = hxs.select("//p")
for title in titles:
self.item ["title"] = title.select("a/text()").extract()
self.item ["link"] = title.select("a/@href").extract()
print ('**parse_items_2:', self.item["title"], self.item["link"])
self.items.append(self.item)
return self.items
非常感谢任何帮助!
谢谢你。