【问题标题】:I can't get the data using Rules on scrapy我无法在 scrapy 上使用规则获取数据
【发布时间】:2014-02-01 10:13:32
【问题描述】:

如果我不实施任何规则,我正在使用scrapy 做一个蜘蛛,但现在我正在尝试实施一个规则来获取分页器并抓取所有其余页面。但我不知道为什么我不能实现它。

蜘蛛码:

    allowed_domains = ['guia.bcn.cat']
    start_urls = ['http://guia.bcn.cat/index.php?pg=search&q=*:*']

rules = (
        Rule(SgmlLinkExtractor(allow=("index.php?pg=search&from=10&q=*:*&nr=10"),
        restrict_xpaths=("//div[@class='paginador']",))
        , callback="parse_item", follow=True),)

def parse_item(self, response)
...

另外,我尝试在规则的允许参数中设置“index.php”,但都不起作用。

我在 scrapy 群组中看到我没有放“a/”或“a/@href”,因为 SgmlLinkExtractor 会自动搜索链接。

控制台输出似乎运行良好,但没有得到任何东西。

有什么想法吗?

提前致谢

编辑:

使用此代码可以工作

from scrapy.selector import Selector
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.contrib.spiders import CrawlSpider, Rule
from bcncat.items import BcncatItem
import re

class BcnSpider(CrawlSpider):
    name = 'bcn'
    allowed_domains = ['guia.bcn.cat']
    start_urls = ['http://guia.bcn.cat/index.php?pg=search&q=*:*']


rules = (
    Rule(
        SgmlLinkExtractor(
            allow=(re.escape("index.php")),
            restrict_xpaths=("//div[@class='paginador']")),
        callback="parse_item",
        follow=True),
)

def parse_item(self, response):
    self.log("parse_item")
    sel = Selector(response)
    i = BcncatItem()
    #i['domain_id'] = sel.xpath('//input[@id="sid"]/@value').extract()
    #i['name'] = sel.xpath('//div[@id="name"]').extract()
    #i['description'] = sel.xpath('//div[@id="description"]').extract()
    return i

【问题讨论】:

    标签: python web-crawler scrapy


    【解决方案1】:

    SgmlLinkExtractorallow 参数是正则表达式的(列表)。所以“?”、“*”和“。”被视为特殊字符。

    您可以使用allow=(re.escape("index.php?pg=search&from=10&q=*:*&nr=10"))(在脚本开头的某处使用import re

    编辑:事实上,上述规则不起作用。但是由于您已经有了要提取链接的受限区域,您可以使用allow=('index.php')

    【讨论】:

    • 如果我使用allow=('index.php') 它什么也做不了
    • 我上传了一个示例 CrawlSpider 和 console.log:gist.github.com/redapple/8405909
    • 现在可以了!也许是关于行索引.. 我不知道 python 究竟是如何工作的,但如果我取消注释一个项目行 #i['domain_id'] = sel.xpath('//input[@id="sid"]/@value').extract() 有时控制台会显示 Indexation Error 并修复它我必须退出一个制表符空间。正常吗?是新手错误吗?非常感谢您的回复和工作!
    • 在 Python 中,代码的缩进是必不可少的,混合 TAB 和空格字符会导致这些错误。要么到处缩进 TAB,要么到处缩进 N 空格,然后坚持下去。 (我个人使用 4 个空格。)
    • 只有更多问题:为什么输出 json 给我这样的东西 {"title": [Film1], ... 而不是 {"title": Film1, ... 或者如果我以 xml 格式导出我有:<title><value>Film1</value></title> 而不是 <title>Film1</title> ?我问这个是因为我必须在 solr 中导入,而且没有 [] 或 字段更清楚。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-10
    • 1970-01-01
    • 1970-01-01
    • 2021-08-12
    • 2015-12-16
    相关资源
    最近更新 更多