【问题标题】:Spider not scraping the right amount of items蜘蛛没有刮取适量的物品
【发布时间】:2015-04-03 06:59:07
【问题描述】:

过去几天我一直在学习 Scrapy,但在获取页面上的所有列表元素时遇到了麻烦。

所以页面有类似这样的结构:

<ol class="list-results">
    <li class="SomeClass i">
        <ul>
            <li class="name">Name1</li>
        </ul>
    </li>
    <li class="SomeClass 0">
        <ul>
            <li class="name">Name2</li>
        </ul>
    </li>
    <li class="SomeClass i">
        <ul>
            <li class="name">Name3/li>
        </ul>
    </li>
</ol>

在 Scrapy 的 Parse 函数中,我得到的所有列表元素是这样的:

def parse(self, response):
        sel = Selector(response)
        all_elements = sel.css('.SomeClass')
        print len(all_elemts)

我知道在我请求的测试页面上有该类的大约 300 个列表元素,但是在打印 len(all_elements) 之后,我只得到 61 >.

我尝试过使用 xpath,例如:

sel.xpath("//*[contains(concat(' ', @class, ' '), 'SomeClass')]")

但我仍然得到了 61 个元素,而不是我应该的 300 个。

此外,我正在使用 try and except claws,以防一个元素给我一个例外。

这是我要抓取的实际页面: https://search.msu.edu/people/index.php?fst=ab&lst=&nid=&filter=

请理解,我这样做只是为了练习!

请帮忙!谢谢!我只是不知道还能做什么!

【问题讨论】:

标签: python xpath css-selectors web-scraping scrapy


【解决方案1】:

恐怕您正在处理格式不正确且损坏的 HTML,Scrapy(以及底层的 lxml)无法可靠地解析。例如,在li 标签内看到这个未封闭的div

<li class="unit"><span>Unit:</span> 
    <div class="unit-block"> Language Program                  
</li>

我会切换到使用 BeautifulSoup 手动解析 HTML。也就是说,继续使用Scrapy框架的所有其他部分和组件,但是HTML解析部分留给BeautifulSoup

来自scrapy shell的演示:

$ scrapy shell "https://search.msu.edu/people/index.php?fst=ab&lst=&nid=&filter="
In [1]: len(response.css('li.student'))
Out[1]: 55

In [2]: from bs4 import BeautifulSoup

In [3]: soup = BeautifulSoup(response.body)

In [4]: len(soup.select('li.student'))
Out[4]: 281

如果您使用的是CrawlSpider,并且需要基于BeautifulSoupLinkExtractor,请参阅:

【讨论】:

  • 非常感谢您发现这一点!我一直在试图弄清楚是什么问题太久了。
猜你喜欢
  • 2018-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多