3

私は自分のウェブサイトをクロールするためにスクレイピーを使用していますhttp://www.cseblog.com

私のスパイダーは次のとおりです。

from scrapy.spider import BaseSpider
from bs4 import BeautifulSoup ## This is BeautifulSoup4
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor

from blogscraper.items import BlogArticle ## This is for saving data. Probably insignificant.

class BlogArticleSpider(BaseSpider):
    name = "blogscraper"
    allowed_domains = ["cseblog.com"]
    start_urls = [
        "http://www.cseblog.com/",
    ]

    rules = (
        Rule(SgmlLinkExtractor(allow=('\d+/\d+/*"', ), deny=( ))),
    )

    def parse(self, response):
        site = BeautifulSoup(response.body_as_unicode())
        items = []
        item = BlogArticle()
        item['title'] = site.find("h3" , {"class": "post-title" } ).text.strip()
        item['link'] = site.find("h3" , {"class": "post-title" } ).a.attrs['href']
        item['text'] = site.find("div" , {"class": "post-body" } )
        items.append(item)
        return items

タイプ http://www.cseblog.com/{d+}/{d+}/{*}.html および http://www.cseblog.com/search のすべてのリンクをクロールする必要があることをどこで指定しますか? /{*} 再帰的に

ただし、 http://www.cseblog.com/ {d+}/{d+}/{*}.htmlからデータを保存します

4

1 に答える 1

1

これらのタイプの URL を許可するには、2 つのルールを作成するか、scrapy に指示する 1 つのルールを作成する必要があります。基本的に、ルールリストは次のようになります

rules = (
        Rule(SgmlLinkExtractor(allow=('http://www.cseblog.com/{d+}/{d+}/{*}.html', ), deny=( )),call_back ='parse_save' ),
        Rule(SgmlLinkExtractor(allow=('http://www.cseblog.com/search/{*}', ), deny=( )),,call_back = 'parse_only' ))

ところで、基本クラスのメソッドをオーバーライドする場合を除き、クロール スパイダーを使用し、解析メソッド名を変更する必要があります。

両方のリンク タイプには異なるコールバックがあります。つまり、どの処理済みページ データを保存するかを決定できます。単一のコールバックを使用して、もう一度 response.url をチェックするのではなく。

于 2013-10-31T15:30:27.660 に答える