2013-02-12 82 views
0

试图让我的webcrawler抓取从网页中提取的链接。我正在使用Scrapy。我可以使用我的抓取工具成功抓取数据,但无法抓取它。我相信问题出在我的规则部分。 Scrapy新手。感谢您提前帮忙。问题以下链接Scrapy

我刮这个网站:

/wiki/index.php/A._Ghani 

/wiki/index.php/A._Keith_Carreiro 

这里:

http://ballotpedia.org/wiki/index.php/Category:2012_challenger 

我试图按照这个样子的源代码的链接是我的蜘蛛的代码:

from scrapy.spider import BaseSpider 
from scrapy.selector import HtmlXPathSelector 
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor 
from scrapy.contrib.spiders import CrawlSpider,Rule 

from ballot1.items import Ballot1Item 

class Ballot1Spider(CrawlSpider): 
    name = "stewie" 
    allowed_domains = ["ballotpedia.org"] 
    start_urls = [ 
     "http://ballotpedia.org/wiki/index.php/Category:2012_challenger" 
    ] 
    rules = (
     Rule (SgmlLinkExtractor(allow=r'w+'), follow=True), 
     Rule(SgmlLinkExtractor(allow=r'\w{4}/\w+/\w+'), callback='parse') 
    ) 

def parse(self, response): 
    hxs = HtmlXPathSelector(response) 
    sites = hxs.select('*') 
    items = [] 
    for site in sites: 
     item = Ballot1Item() 
     item['candidate'] = site.select('/html/head/title/text()').extract() 
     item['position'] = site.select('//table[@class="infobox"]/tr/td/b/text()').extract() 
     item['controversies'] = site.select('//h3/span[@id="Controversies"]/text()').extract() 
     item['endorsements'] = site.select('//h3/span[@id="Endorsements"]/text()').extract() 
     item['currentposition'] = site.select('//table[@class="infobox"]/tr/td[@style="text-align:center; background-color:red;color:white; font-size:100%; font-weight:bold;"]/text()').extract() 
     items.append(item) 
    return items 

回答

0

r'w+'是错误的(我认为你的意思r'\w+')和r'\w{4}/\w+/\w+'看起来不正确也是如此,因为它不符合你的链接(它缺少一个龙头/)。你为什么不试试r'/wiki/index.php/.+'? 不要忘记,\w不包括.和其他符号,可以是文章名称的一部分。

+0

嘿,非常感谢。我现在就试试。 – 2013-02-12 00:52:19

+0

刚刚尝试了上述对规则的更改。它仍然只报废我的起始网址。 – 2013-02-12 00:55:20

1

那你后的链接是只有在这个元素存在:

<div lang="en" dir="ltr" class="mw-content-ltr"> 

所以,你必须限制XPath来防止外部链接:

restrict_xpaths='//div[@id="mw-pages"]/div' 

最后,你只是想请按照看起来像/wiki/index.php?title=Category:2012_challenger&pagefrom=Alison+McCoy#mw-pages的链接,因此您的最终规则应如下所示:

rules = (
    Rule(
     SgmlLinkExtractor(
      allow=r'&pagefrom=' 
     ), 
     follow=True 
    ), 
    Rule(
     SgmlLinkExtractor(
      restrict_xpaths='//div[@id="mw-pages"]/div', 
      callback='parse' 
     ) 
    ) 
) 
+0

感谢搅拌机。我马上试一试。 – 2013-02-12 00:56:53

+0

@YoungGrasshopper:看我的编辑。 “允许”规则不正确。 – Blender 2013-02-12 00:58:42

+0

添加此代码引发了无效的表达式错误。它也说不好的字符范围。这听起来很熟悉@Blender – 2013-02-12 01:06:42