簡體   English   中英

Scrapy Spider 未正確抓取數據

[英]Scrapy spider not scraping the data correctly

我正在嘗試使用scrapy從我的大學網站上抓取有關項目的循環數據,但我的蜘蛛沒有正確抓取數據。 有很多空白元素,而且由於某種原因我無法刮取循環的“href”屬性。 我假設我的 CSS 選擇器是錯誤的,但我無法弄清楚我到底做錯了什么。 我使用“Selector Gadget”Chrome 擴展程序復制了我的 CSS 選擇器。 我一直在學習scrapy,所以如果你能解釋我做錯了什么,那就太好了。

我從中抓取數據的網站是: https : //www.imsnsit.org/imsnsit/notifications.php

我的代碼是:

import scrapy
from ..items import CircularItem

class CircularSpider(scrapy.Spider):
    name = "circular"
    start_urls = [
        "https://www.imsnsit.org/imsnsit/notifications.php"
    ]

    def parse(self, response):
        items = CircularItem()
        all = response.css('tr~ tr+ tr font')
        for x in all:
            cirName = x.css('a font::text').extract()
            cirLink = x.css('.list-data-focus a').attrib['href'].extract()
            date = x.css('tr~ tr+ tr td::text').extract()
            items["Name"] = cirName
            items["href"] = cirLink
            items["Date"] = date
            yield items

我修改了你的解析回調函數。 我將 CSS 選擇器更改為 xpath。 此外,嘗試學習xpath 選擇器,它們非常強大且易於使用。 通常,使用自動選擇器復制 CSS 或 xpath 是個壞主意,因為在某些情況下,它們可能會給您不正確的結果或只有一個沒有通用路徑的元素。

首先,我選擇所有tr 如果仔細觀察,某些tr只是用作分隔符的空白。 您可以通過嘗試選擇date來過濾它們,如果它是None您可以跳過該行。 最后你可以選擇cirNamecirLink

此外,給定網站的標記不好,編寫合適的選擇器真的很難,元素沒有很多屬性,比如classid 這是我想出的解決方案,我知道它並不完美。

def parse(self, response):
    items = CircularItem()
    all = response.xpath('//tr') # select all table items
    for x in all:
        date = x.xpath('.//td/font[@size="3"]/text()').get() # filter them by date
        if not date:
            continue
        cirName = x.xpath('.//a/font/text()').get()
        cirLink = x.xpath('.//a[@title="NOTICES / CIRCULARS"]/@href').get()
        items["Name"] = cirName
        items["href"] = cirLink
        items["Date"] = date
        yield items

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM