爬蟲9:Scrapy-獲取steam網站前50頁游戲的url


第一步先確定下steam網站游戲的URLs

http://store.steampowered.com/search/?page=1

把這個url作為我們的start_urls

from scrapy.spiders import Spider
from scrapy.selector import Selector


class SteamUrls(Spider):
    name = "steamurl"
    allowed_domains = ["steampowered.com"]
    start_urls=[
        "http://store.steampowered.com/search/?page=1"
    ]
    def parse(self,response):
        sel = Selector(response)
        links = sel.xpath("//a[@class='search_result_row ds_collapse_flag app_impression_tracked']/@href").extract()
        for link in links:
            print link
            
            

然后先獲取第一頁的所有游戲的urls,然而我發現這樣毛都打印不出來,想了一下,FirePath定位到了,取值也沒有錯,阿西吧,為什么會打印不出內容呢。

后來求助於程序員GG

發現了一個問題:爬蟲所看到的是網頁的源碼,而我在用firefox的FirePath定位元素時,是基於網頁渲染完成的基礎上的

這兩者還是有一定的區別,以前我在用xpath定位的經驗是在做自動化測試,用selenium基礎上的,而selenium的基礎便是建立在網頁已經渲染完成的基礎上的

所以我修改了一下xpath的寫法

from scrapy.spiders import Spider
from scrapy.selector import Selector


class Steanyurls(Spider):
    name = "steamurl"
    allowed_domains = ["steampowered.com"]
    start_urls=[
        "http://store.steampowered.com/search/?page=1"
    ]
    def parse(self,response):
        sel = Selector(response)
        links = sel.xpath("//div[@id='search_result_container']/div[2]//@href").extract()
        for link in links:
            print link
            
            

這樣便獲取到了第一頁的25條數據

然后新設置一個循環,爬取其余頁面的數據,這里用到了一個yield函數

from scrapy.spiders import Spider
from scrapy.selector import Selector
from scrapy.http import Request


class SteamUrls(Spider):
    name = "steamurl"
    allowed_domains = ["steampowered.com"]
    start_urls=[
        "http://store.steampowered.com/search/?page=1"
    ]
    def parse(self,response):
        sel = Selector(response)
        links = sel.xpath("//div[@id='search_result_container']/div[2]//@href").extract()
        for link in links:
            print link
        PageList= range(2,11)
        for i in PageList:
             url2='http://store.steampowered.com/search/?page='+str(i)
             yield Request(url2,callback=self.parse)
            
            

這里爬出來沒有按照規則,比如先爬取了第八頁的數據,然后爬取了第五頁的數據,請教過后說是沒有默認的順序,給了url就會去爬

 

到目前為止不打算在繼續寫爬蟲的日志了,這里僅僅是很多框架的demo

解析網頁的東西就太多了,會見招拆招了


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM