Skip to main content
 首页 » 编程设计

python之Scrapy 只抓取每页的第一个结果

2024年11月01日10lvdongjie

我目前正在尝试运行以下代码,但它一直只抓取每个页面的第一个结果。知道可能是什么问题吗?

from scrapy.contrib.spiders import CrawlSpider, Rule 
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor 
from scrapy.selector import HtmlXPathSelector 
from firstproject.items import xyz123Item 
import urlparse 
from scrapy.http.request import Request 
 
class MySpider(CrawlSpider): 
    name = "xyz123" 
    allowed_domains = ["www.xyz123.com.au"] 
    start_urls = ["http://www.xyz123.com.au/",] 
 
    rules = (Rule (SgmlLinkExtractor(allow=("",),restrict_xpaths=('//*[@id="1234headerPagination_hlNextLink"]',)) 
    , callback="parse_xyz", follow=True), 
    ) 
 
    def parse_xyz(self, response): 
        hxs = HtmlXPathSelector(response) 
        xyz = hxs.select('//div[@id="1234SearchResults"]//div/h2') 
        items = [] 
        for xyz in xyz: 
            item = xyz123Item() 
            item ["title"] = xyz.select('a/text()').extract()[0] 
            item ["link"] = xyz.select('a/@href').extract()[0] 
            items.append(item) 
            return items 

Basespider 版本可以很好地抓取第一页上的所有必需数据:

from scrapy.spider import BaseSpider 
from scrapy.selector import HtmlXPathSelector 
from firstproject.items import xyz123 
 
class MySpider(BaseSpider): 
    name = "xyz123test" 
    allowed_domains = ["xyz123.com.au"] 
    start_urls = ["http://www.xyz123.com.au/"] 
 
 
    def parse(self, response): 
        hxs = HtmlXPathSelector(response) 
        titles = hxs.select('//div[@id="1234SearchResults"]//div/h2') 
        items = [] 
        for titles in titles: 
            item = xyz123Item() 
            item ["title"] = titles.select("a/text()").extract() 
            item ["link"] = titles.select("a/@href").extract() 
            items.append(item) 
        return items 

抱歉审查。出于隐私原因,我不得不审查该网站。

第一个代码以我希望的方式很好地爬过页面,但它只提取第一个项目的标题和链接。注意:第一个在 google 中使用“inspect element”的标题的 XPath 是:
//*[@id="xyz123SearchResults"]/div[1]/h2/a,
第二个是 //*[@id="xyz123SearchResults"]/div[2]/h2/a
第三个是//*[@id="xyz123SearchResults"]/div[3]/h2/a等

我不确定是不是 div[n] 位导致了它的崩溃。我希望这是一个简单的修复。

谢谢

请您参考如下方法:

 for xyz in xyz: 
            item = xyz123Item() 
            item ["title"] = xyz.select('a/text()').extract()[0] 
            item ["link"] = xyz.select('a/@href').extract()[0] 
            items.append(item) 
            return items 

您确定返回商品的缩进吗?应该少一个。