python - Scrapy蜘蛛索引错误

标签 python web-crawler scrapy

这是我一直试图在 Scrapy 框架内编写的 Spyder1 的代码:

from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import HtmlXPathSelector
from scrapy.item import Item
from firm.items import FirmItem

class Spider1(CrawlSpider):
    domain_name = 'wc2'
    start_urls = ['http://www.whitecase.com/Attorneys/List.aspx?LastName=A']
    rules = (
        Rule(SgmlLinkExtractor(allow=["hxs.select(
            '//td[@class='altRow'][1]/a/@href').re('/.a\w+')"]), 
            callback='parse'),
    )

    def parse(self, response):
        hxs = HtmlXPathSelector(response)
        JD = FirmItem()
        JD['school'] = hxs.select(
                   '//td[@class="mainColumnTDa"]').re('(?<=(JD,\s))(.*?)(\d+)'
        )
        return JD    

SPIDER = Spider1()

rules 中的正则表达式成功地从起始 url 中提取了我想要的所有 bio url:

>>> hxs.select(
...             '//td[@class="altRow"][1]/a/@href').re('/.a\w+')
[u'/cabel', u'/jacevedo', u'/jacuna', u'/aadler', u'/zahmedani', u'/tairisto', u
'/zalbert', u'/salberts', u'/aaleksandrova', u'/malhadeff', u'/nalivojvodic', u'
/kallchurch', u'/jalleyne', u'/lalonzo', u'/malthoff', u'/valvarez', u'/camon',
u'/randerson', u'/eandreeva', u'/pangeli', u'/jangland', u'/mantczak', u'/darany
i', u'/carhold', u'/marora', u'/garrington', u'/jartzinger', u'/sasayama', u'/ma
sschenfeldt', u'/dattanasio', u'/watterbury', u'/jaudrlicka', u'/caverch', u'/fa
yanruoh', u'/razar']
>>>

但是当我运行代码时我得到了

[wc2] ERROR: Error processing FirmItem(school=[]) - 

[Failure instance: Traceback: <type 'exceptions.IndexError'>: list index out of range

这是 Items.py 中的 FirmItem

from scrapy.item import Item, Field

class FirmItem(Item):
    school = Field()

    pass

你能帮我了解索引错误发生在哪里吗?

在我看来,它与SgmLinkExtractor有关。 .

数周以来,我一直在尝试使用 Scrapy 使这个蜘蛛工作。他们有一个很好的教程,但我是 python 和网络编程的新手,所以我不明白例如 SgmlLinkExtractor 是如何在幕后工作的。

尝试使用 Python 库编写具有相同简单功能的爬虫对我来说会更容易吗?如果有任何意见和帮助,我将不胜感激。

谢谢

最佳答案

SgmlLinkExtractor 在其“允许”参数中不支持选择器。

所以这是错误的:

SgmlLinkExtractor(allow=["hxs.select('//td[@class='altRow'] ...')"])

这是对的:

SgmlLinkExtractor(allow=[r"product\.php"])

关于python - Scrapy蜘蛛索引错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1805050/

相关文章:

python - Scrapy: 'str' 对象没有属性 'iter'

javascript - 在 python-vtk/three.js 中居中多数据模型的轴/枢轴

python - 带有谷歌身份工具包的谷歌云端点

architecture - 如何使用动态数据启用页面索引?

php - 使用 php 抓取 html 页面?

python - 我如何查看/获取 scrapy POST/GET 请求 header

python - pandas read_excel(sheet name = None) 返回一个字符串字典,而不是数据框?

java - python - 什么是最大字节相当于 java Byte.MAX_VALUE

python - 使用 python 3 的 Selenium 中的 WebDriverException

python - Scrapy 在基本示例上崩溃(无法运行)