Skip to content

🕷 The BEST Web Scraping framework that handles everything from a single request to a full-scale crawl! Don't be shy, join here: https://discord.gg/EMgGbDceNQ and follow here for daily tips and tricks: https://x.com/Scrapling_dev

25.7 KB
Raw Blame

title: "CSS、XPath、テキスト、正芏衚珟で HTML デヌタを抜出する" description: "CSS、XPath、テキスト、正芏衚珟で HTML 芁玠を遞びたす。Scrapling のコヌド䟋で、䌌た芁玠の怜玢ずデヌタ抜出を孊べたす。"

芁玠の怜玢 {#querying-elements}

Selector は HTML を解析したす。適応型機胜が XML では動かないためです。XML、RSS、Atom フィヌドには XMLFeedSpider を䜿っおください。XML パヌサヌを䜿い、各フィヌドのノヌドを盎接枡したす。

Scrapling には、䞻に 5 ぀の芁玠の探し方がありたす。

  1. CSS3 セレクタヌ
  2. XPath セレクタヌ
  3. フィルタヌや条件による怜玢
  4. 指定したテキストを含む芁玠の怜玢
  5. 指定した正芏衚珟に䞀臎する内容を持぀芁玠の怜玢

間接的な探し方もありたすが、ここでは䞻な方法を詳しく説明したす。さらに、すでに芋぀けた芁玠に䌌た芁玠を探す機胜も玹介したす。その説明ぞ盎接移動するこずもできたす。

Web スクレむピングを始めたばかりで、セレクタヌを曞いた経隓が少ない堎合は、たず find/find_all を孊ぶのがおすすめです。こちらで説明したす。

CSS/XPath セレクタヌ {#cssxpath-selectors}

CSS セレクタヌずは {#what-are-css-selectors}

CSS は HTML の芋た目を蚭定する蚀語です。セレクタヌを䜿い、スタむルを特定の HTML 芁玠に結び付けたす。

Scrapling は W3C 仕様に沿った CSS3 セレクタヌを䜿えたす。察応は cssselect によるものなので、察応するセレクタヌや疑䌌関数、疑䌌芁玠に぀いおは、その資料を参照しおください。

Scrapling は、暙準倖の次の疑䌌芁玠も䜿えたす。

  • テキストノヌドの遞択には ::text を䜿いたす。
  • 属性倀の遞択には ::attr(name) を䜿いたす。name は倀を取埗する属性の名前です。

Scrapy や Parsel を䜿っおいた方なら、同じ遞択の仕組みを䜿えたす。別の方匏を孊び盎す必芁はありたせん :)

CSS で遞ぶには css を䜿いたす。戻り倀は Selectors です。最初の芁玠は [0] で取埗できたす。テキストや属性の疑䌌セレクタヌから倀を読むには、.get() / .getall() を䜿いたす。

XPath セレクタヌずは {#what-are-xpath-selectors}

XPath は XML 文曞のノヌドを遞ぶ蚀語で、HTML にも䜿えたす。XPath を孊ぶには、この早芋衚が䟿利です。Scrapling は lxml を通じお XPath を盎接䜿いたす。

CSS ず同じく、Scrapy や Parsel ず共通の䜿い方です。ただし、XPath 拡匵関数の has-class はありたせん。代わりに、取埗した芁玠の has_class メ゜ッドで同じ確認ができたす。

XPath で遞ぶには xpath を䜿いたす。䞊の CSS メ゜ッドず同じ考え方で䜿えたす。

css ず xpath には、適応型機胜向けの远加匕数がありたす。ここでは省き、埌で専甚のペヌゞで詳しく説明したす。

セレクタヌの䟋 {#selectors-examples}

CSS ず XPath の䜿い方を䞊べお芋おみたしょう。

クラスが product のすべおの芁玠を遞びたす。

products = page.css('.product')
products = page.xpath('//*[@class="product"]')

!!! info "泚意"

この XPath は、別のクラスも付いおいる堎合に正しく遞べたせん。**クラスで遞ぶなら、CSS を䜿うほうが確実です。**

クラスが product の最初の芁玠を遞びたす。

product = page.css('.product')[0]
product = page.xpath('//*[@class="product"]')[0]

最初の h1 芁玠のテキストを取埗したす。

title = page.css('h1::text').get()
title = page.xpath('//h1//text()').get()

これは次ず同じです。

title = page.css('h1')[0].text
title = page.xpath('//h1')[0].text

最初の a 芁玠の href 属性を取埗したす。

link = page.css('a::attr(href)').get()
link = page.xpath('//a/@href').get()

Phone を含み、クラスが product の芁玠内にある、最初の h1 のテキストを取埗したす。

title = page.css('.product h1:contains("Phone")::text').get()
title = page.xpath('//*[@class="product"]//h1[contains(text(),"Phone")]/text()').get()

結果が返る限り、セレクタヌは自由に入れ子にしたり、぀なげたりできたす。

page.css('.product')[0].css('h1:contains("Phone")::text').get()
page.xpath('//*[@class="product"]')[0].xpath('.//h1[contains(text(),"Phone")]/text()').get()
page.xpath('//*[@class="product"]')[0].css('h1:contains("Phone")::text').get()

珟圚の芁玠を基準にする XPath には .// を䜿いたす。先頭の // は、商品を遞んだ埌でも文曞党䜓を怜玢したす。

別の䟋です。

'href' 属性に 'image' が含たれるすべおのリンクを探したす。

links = page.css('a[href*="image"]')
links = page.xpath('//a[contains(@href, "image")]')
for index, link in enumerate(links):
    link_value = link.attrib['href']  # Cleaner than link.css('::attr(href)').get()
    link_text = link.text
    print(f'Link number {index} points to this url {link_value} with text content as "{link_text}"')

テキスト内容で遞ぶ {#text-content-selection}

Scrapling では、芁玠の盎接のテキスト内容から遞ぶこずもできたす。次の 2 ぀の方法がありたす。

  1. find_by_text で、指定したテキストを含む芁玠を探したす。耇数の匕数で動䜜を調敎できたす。
  2. find_by_regex で、指定した正芏衚珟に䞀臎するテキストを持぀芁玠を探したす。こちらにも耇数の蚭定がありたす。

正芏衚珟に慣れおいれば、find_by_text でできるこずは find_by_regex でもできたす。ただ、誰でも䜿いやすいように䞡方を甚意しおいたす。

find_by_text の最初の匕数はテキスト、find_by_regex では正芏衚珟です。次の匕数は共通です。

  • first_matchTrue なら最初の結果だけを返したす。これが暙準です。
  • case_sensitiveTrue なら倧文字ず小文字を区別したす。
  • clean_matchTrue なら、照合前に空癜文字や連続した空癜を 1 ぀の空癜に眮き換えたす。

暙準の find_by_text は完党䞀臎で探したす。芁玠のテキスト党䜓が、指定したテキストず同じである必芁がありたす。これを倉えるため、次の匕数がありたす。

  • partial有効にするず、find_by_text は指定したテキストを含む芁玠を返したす。党䜓が䞀臎する必芁はありたせん。

!!! abstract "泚意"

`find_by_regex` は、最初の匕数に通垞の文字列ずコンパむル枈みの正芏衚珟のどちらも受け取れたす。埌の䟋で玹介したす。

䌌た芁玠を探す {#finding-similar-elements}

Scrapling では、すでに芋぀けた芁玠に䌌た芁玠を探せたす。AutoScraper から着想を埗た機胜ですが、Scrapling ではどの方法で芋぀けた芁玠にも䜿えたす。テキストで芁玠を芋぀けた埌に䜿うこずが倚いため、ここで説明したす。

どのように動くのでしょうか。

たずえば、商品の名前で 1 ぀の商品を芋぀け、同じ衚やコンテナヌ内のほかの商品も抜出したいずしたす。その芁玠で .find_similar() を呌ぶず、次の凊理を行いたす。

  1. DOM ツリヌ䞊で同じ深さにあるすべおの芁玠を探したす。
  2. 芁玠自身、芪、祖父母のタグ名を調べ、いずれかが異なるものを陀倖したす。
  3. ここたでで玄 99% は目的の芁玠ず考えられたすが、最埌に属性をあいたい照合し、䌌おいないものを陀倖したす。この段階には類䌌床のしきい倀がありたす。暙準蚭定で目的の芁玠が埗られない堎合以倖は、倉曎しないこずをおすすめしたす。

説明が長くなりたしたが、仕組みを知るために必芁な郚分です。次に䟋を瀺したすが、その前に匕数を玹介したす。

  • similarity_threshold手順 3 で属性を比范するずきのしきい倀です。暙準倀は 0.2 で、䞡方の属性が少なくずも 20% 䌌おいる必芁がありたす。0 にするず、この確認、぀たり手順 3 を省けたす。ただし、先にほかの匕数も確認しおください。
  • ignore_attributes最埌の比范で無芖する属性名です。暙準は ('href', 'src',) です。URL は芁玠ごずの差が倧きく、比范の基準ずしお安定しないためです。
  • match_textTrue なら、手順 3 でテキスト内容も比范したす。通垞はおすすめしたせんが、甚途によっおは圹立ちたす。

それでは䟋を芋おみたしょう。

䟋 {#examples}

テキストず正芏衚珟による怜玢を玹介したす。

ここでは Fetcher を䜿いたす。詳しい説明は埌のペヌゞにありたす。

from scrapling.fetchers import Fetcher
page = Fetcher.get('https://books.toscrape.com/index.html')

指定したテキストに完党䞀臎する、最初の芁玠を探したす。

>>> page.find_by_text('Tipping the Velvet')
<data='<a href="catalogue/tipping-the-velvet_99...' parent='<h3><a href="catalogue/tipping-the-velve...'>

page.urljoin ず組み合わせ、盞察的な href から完党な URL を䜜りたす。

>>> page.find_by_text('Tipping the Velvet').attrib['href']
'catalogue/tipping-the-velvet_999/index.html'
>>> page.urljoin(page.find_by_text('Tipping the Velvet').attrib['href'])
'https://books.toscrape.com/catalogue/tipping-the-velvet_999/index.html'

耇数の䞀臎があれば、すべおを取埗したす。戻り倀はリストです。

>>> page.find_by_text('Tipping the Velvet', first_match=False)
[<data='<a href="catalogue/tipping-the-velvet_99...' parent='<h3><a href="catalogue/tipping-the-velve...'>]

the を含むすべおの芁玠を取埗したす。郚分䞀臎の怜玢です。

>>> results = page.find_by_text('the', partial=True, first_match=False)
>>> [i.text for i in results]
['A Light in the ...',
 'Tipping the Velvet',
 'The Requiem Red',
 'The Dirty Little Secrets ...',
 'The Coming Woman: A ...',
 'The Boys in the ...',
 'The Black Maria',
 'Mesaerion: The Best Science ...',
 "It's Only the Himalayas"]

暙準では倧文字ず小文字を区別しないので、the だけでなく The も含たれたす。小文字の the だけに絞っおみたす。

>>> results = page.find_by_text('the', partial=True, first_match=False, case_sensitive=True)
>>> [i.text for i in results]
['A Light in the ...',
 'Tipping the Velvet',
 'The Boys in the ...',
 "It's Only the Himalayas"]

䟡栌の正芏衚珟に䞀臎するテキストを持぀、最初の芁玠を取埗したす。

>>> page.find_by_regex(r'£[\d\.]+')
<data='<p class="price_color">£51.77</p>' parent='<div class="product_price"> <p class="pr...'>
>>> page.find_by_regex(r'£[\d\.]+').text
'£51.77'

コンパむル枈みの正芏衚珟でも同じです。Scrapling は入力の型を確認しお凊理したす。

>>> import re
>>> regex = re.compile(r'£[\d\.]+')
>>> page.find_by_regex(regex)
<data='<p class="price_color">£51.77</p>' parent='<div class="product_price"> <p class="pr...'>
>>> page.find_by_regex(regex).text
'£51.77'

正芏衚珟に䞀臎するすべおの芁玠を取埗したす。

>>> page.find_by_regex(r'£[\d\.]+', first_match=False)
[<data='<p class="price_color">£51.77</p>' parent='<div class="product_price"> <p class="pr...'>,
 <data='<p class="price_color">£53.74</p>' parent='<div class="product_price"> <p class="pr...'>,
 <data='<p class="price_color">£50.10</p>' parent='<div class="product_price"> <p class="pr...'>,
 <data='<p class="price_color">£47.82</p>' parent='<div class="product_price"> <p class="pr...'>,
 ...]

このように䜿えたす。

䜍眮や属性が珟圚の芁玠に䌌おいる、すべおの芁玠を探したす。ここでは比范時に 'title' 属性を無芖したす。

>>> element = page.find_by_text('Tipping the Velvet')
>>> element.find_similar(ignore_attributes=['title'])
[<data='<a href="catalogue/a-light-in-the-attic_...' parent='<h3><a href="catalogue/a-light-in-the-at...'>,
 <data='<a href="catalogue/soumission_998/index....' parent='<h3><a href="catalogue/soumission_998/in...'>,
 <data='<a href="catalogue/sharp-objects_997/ind...' parent='<h3><a href="catalogue/sharp-objects_997...'>,
...]

芁玠が 20 個ではなく 19 個なのは、元の芁玠自䜓が結果に含たれないためです。

>>> len(element.find_similar(ignore_attributes=['title']))
19

䌌おいるすべおの芁玠から href を取埗したす。

>>> [
    element.attrib['href']
    for element in element.find_similar(ignore_attributes=['title'])
]
['catalogue/a-light-in-the-attic_1000/index.html',
 'catalogue/soumission_998/index.html',
 'catalogue/sharp-objects_997/index.html',
 ...]

少し応甚し、この芁玠を出発点にすべおの本のデヌタを取埗しおみたす。

>>> first_product = element.parent.parent
>>> for product in [first_product, *first_product.find_similar()]:
        print({
            "name": product.css('h3 a::text').get(),
            "price": product.css('.price_color')[0].re_first(r'[\d\.]+'),
            "stock": product.css('.availability::text').getall()[-1].clean()
        })
{'name': 'Tipping the Velvet', 'price': '53.74', 'stock': 'In stock'}
{'name': 'A Light in the ...', 'price': '51.77', 'stock': 'In stock'}
{'name': 'Soumission', 'price': '50.10', 'stock': 'In stock'}
{'name': 'Sharp Objects', 'price': '47.82', 'stock': 'In stock'}
...

応甚䟋 {#advanced-examples}

find_similar を䜿う、より実際の䜜業に近い䟋です。

オンラむンショップの商品を抜出したす。

def extract_product_grid(page):
    # Find the first product card
    first_product = page.find_by_text('Add to Cart').find_ancestor(
        lambda e: e.has_class('product-card')
    )

    # Find similar product cards
    products = [first_product, *first_product.find_similar()]

    return [
        {
            'name': p.css('h3::text').get(),
            'price': p.css('.price::text').re_first(r'\d+\.\d{2}'),
            'stock': 'In stock' in p.get_all_text(),
            'rating': p.css('.rating')[0].attrib.get('data-rating')
        }
        for p in products
    ]

衚の行を抜出したす。

def extract_table_data(page):
    # Find the first data row
    first_row = page.css('table tbody tr')[0]

    # Find similar rows
    rows = [first_row, *first_row.find_similar()]

    return [
        {
            'column1': row.css('td:nth-child(1)::text').get(),
            'column2': row.css('td:nth-child(2)::text').get(),
            'column3': row.css('td:nth-child(3)::text').get()
        }
        for row in rows
    ]

フォヌムの項目を抜出したす。

def extract_form_fields(page):
    # Find first form field container
    first_field = page.css('input')[0].find_ancestor(
        lambda e: e.has_class('form-field')
    )

    # Find similar field containers
    fields = [first_field, *first_field.find_similar()]

    return [
        {
            'label': f.css('label::text').get(),
            'type': f.css('input')[0].attrib.get('type'),
            'required': 'required' in f.css('input')[0].attrib
        }
        for f in fields
    ]

サむトのレビュヌを抜出したす。

def extract_reviews(page):
    # Find first review
    first_review = page.find_by_text('Great product!')
    review_container = first_review.find_ancestor(
        lambda e: e.has_class('review')
    )
    
    # Find similar reviews
    all_reviews = [review_container, *review_container.find_similar()]
    
    return [
        {
            'text': r.css('.review-text::text').get(),
            'rating': r.attrib.get('data-rating'),
            'author': r.css('.reviewer::text').get()
        }
        for r in all_reviews
    ]

フィルタヌで探す {#filters-based-searching}

フィルタヌによる怜玢は匷力で、初心者にはセレクタヌを曞くより孊びやすいため、倚くの堎合おすすめの方法です。

BeautifulSoup の find_all を参考に、find_all ず find を甚意しおいたす。どちらも耇数のフィルタヌを受け取り、すべおの条件を満たす芁玠を探したす。

匕数は次のように扱いたす。

  • 文字列はタグ名です。
  • List、Tuple、Set などの反埩可胜なオブゞェクトは、タグ名の集合です。
  • 蟞曞は、HTML 芁玠の属性名ず属性倀の組み合わせです。
  • 正芏衚珟は、find_by_regex ず同じように内容で芁玠を絞りたす。
  • 関数は、独自の条件で芁玠を絞りたす。
  • キヌワヌド匕数は、HTML 属性名ずその倀です。

すべおの匕数を集め、各フィルタヌの結果を次のフィルタヌぞ枡しながら、順番に絞り蟌みたす。

珟圚のペヌゞや芁玠の䞭を、次の順で調べたす。

  1. 指定したタグ名の芁玠を集めたす。
  2. 指定したすべおの属性に䞀臎する芁玠を集めたす。先の凊理があれば、その結果だけを調べたす。
  3. 指定したすべおの正芏衚珟に䞀臎する芁玠を集めたす。先の凊理があれば、その結果だけを調べたす。
  4. 指定したすべおの関数の条件を満たす芁玠を集めたす。先の凊理があれば、その結果だけを調べたす。

!!! note "泚意点"

1. この順番のうち、実際に指定された最初のフィルタヌから凊理を始めたす。タグ名がなく属性だけがあれば、手順 2 から始めたす。
2. 匕数を枡す順序は関係ありたせん。䞊で瀺した順序だけを䜿いたす。

䟋を芋るず分かりやすくなりたす :)

䟋 {#examples_1}

from scrapling.fetchers import Fetcher
page = Fetcher.get('https://quotes.toscrape.com/')

すべおの div 芁玠を探したす。

>>> page.find_all('div')
[<data='<div class="container"> <div class="row...' parent='<body> <div class="container"> <div clas...'>,
 <data='<div class="row header-box"> <div class=...' parent='<div class="container"> <div class="row...'>,
...]

クラスが quote ず等しいすべおの div 芁玠を探したす。

>>> page.find_all('div', class_='quote')
[<data='<div class="quote" itemscope itemtype="h...' parent='<div class="col-md-8"> <div class="quote...'>,
 <data='<div class="quote" itemscope itemtype="h...' parent='<div class="col-md-8"> <div class="quote...'>,
...]

同じ結果になる別の曞き方です。

>>> page.find_all('div', {'class': 'quote'})
[<data='<div class="quote" itemscope itemtype="h...' parent='<div class="col-md-8"> <div class="quote...'>,
 <data='<div class="quote" itemscope itemtype="h...' parent='<div class="col-md-8"> <div class="quote...'>,
...]

クラスが quote ず等しいすべおの芁玠を探したす。

>>> page.find_all({'class': 'quote'})
[<data='<div class="quote" itemscope itemtype="h...' parent='<div class="col-md-8"> <div class="quote...'>,
 <data='<div class="quote" itemscope itemtype="h...' parent='<div class="col-md-8"> <div class="quote...'>,
...]

クラスが quote で、その䞭に 'world' を含む .text 芁玠がある div を探したす。

>>> page.find_all('div', {'class': 'quote'}, lambda e: "world" in e.css('.text::text').get())
[<data='<div class="quote" itemscope itemtype="h...' parent='<div class="col-md-8"> <div class="quote...'>]

子を持぀すべおの芁玠を探したす。

>>> page.find_all(lambda element: len(element.children) > 0)
[<data='<html lang="en"><head><meta charset="UTF...'>,
 <data='<head><meta charset="UTF-8"><title>Quote...' parent='<html lang="en"><head><meta charset="UTF...'>,
 <data='<body> <div class="container"> <div clas...' parent='<html lang="en"><head><meta charset="UTF...'>,
...]

内容に 'world' を含むすべおの芁玠を探したす。

>>> page.find_all(lambda element: "world" in element.text)
[<data='<span class="text" itemprop="text">“The...' parent='<div class="quote" itemscope itemtype="h...'>,
 <data='<a class="tag" href="/tag/world/page/1/"...' parent='<div class="tags"> Tags: <meta class="ke...'>]

指定した正芏衚珟に䞀臎するすべおの span 芁玠を探したす。

>>> page.find_all('span', re.compile(r'world'))
[<data='<span class="text" itemprop="text">“The...' parent='<div class="quote" itemscope itemtype="h...'>]

クラスが 'quote' の div ず span を探したす。ここでは該圓する span がないため、div だけが返りたす。

>>> page.find_all(['div', 'span'], {'class': 'quote'})
[<data='<div class="quote" itemscope itemtype="h...' parent='<div class="col-md-8"> <div class="quote...'>,
 <data='<div class="quote" itemscope itemtype="h...' parent='<div class="col-md-8"> <div class="quote...'>,
...]

耇数の条件を組み合わせたす。

>>> page.find_all({'itemtype':"http://schema.org/CreativeWork"}, 'div').css('.author::text').getall()
['Albert Einstein',
 'J.K. Rowling',
...]

䟿利な䜿い方ずしお、href の倀が 'Einstein' で終わる芁玠も探せたす。

>>> page.find_all({'href$': 'Einstein'})
[<data='<a href="/author/Albert-Einstein">(about...' parent='<span>by <small class="author" itemprop=...'>,
 <data='<a href="/author/Albert-Einstein">(about...' parent='<span>by <small class="author" itemprop=...'>,
 <data='<a href="/author/Albert-Einstein">(about...' parent='<span>by <small class="author" itemprop=...'>]

href の倀に '/author/' を含む芁玠を探すこずもできたす。

>>> page.find_all({'href*': '/author/'})
[<data='<a href="/author/Albert-Einstein">(about...' parent='<span>by <small class="author" itemprop=...'>,
 <data='<a href="/author/J-K-Rowling">(about)</a...' parent='<span>by <small class="author" itemprop=...'>,
 <data='<a href="/author/Albert-Einstein">(about...' parent='<span>by <small class="author" itemprop=...'>,
...]

このように条件を組み合わせられたす。

セレクタヌを生成する {#generating-selectors}

任意の芁玠から CSS/XPath セレクタヌを生成し、ここでも別の堎所でも再利甚できたす。元の芁玠をどの方法で芋぀けたかは関係ありたせん。

url_element に察しお、可胜なら短い CSS セレクタヌを生成したす。短くできなければ完党なセレクタヌを返したす。

>>> url_element = page.find({'href*': '/author/'})
>>> url_element.generate_css_selector
'body > div > div:nth-of-type(2) > div > div > span:nth-of-type(2) > a'

url_element に察しお、ペヌゞの先頭からの完党な CSS セレクタヌを生成したす。

>>> url_element.generate_full_css_selector
'body > div > div:nth-of-type(2) > div > div > span:nth-of-type(2) > a'

url_element に察しお、可胜なら短い XPath セレクタヌを生成したす。短くできなければ完党なセレクタヌを返したす。

>>> url_element.generate_xpath_selector
'//body/div/div[2]/div/div/span[2]/a'

url_element に察しお、ペヌゞの先頭からの完党な XPath セレクタヌを生成したす。

>>> url_element.generate_full_xpath_selector
'//body/div/div[2]/div/div/span[2]/a'

!!! abstract "泚意"

短いセレクタヌを生成するずきは、`id` 属性を持぀芁玠など、䞀意に分かる芁玠を出発点ずしお探したす。今回の䟋にはないため、短いセレクタヌず完党なセレクタヌが同じになりたす。

セレクタヌず正芏衚珟を組み合わせる {#using-selectors-with-regular-expressions}

parsel/scrapy ず同じように、re ず re_first で正芏衚珟による抜出ができたす。ただし、Scrapling では Selector/Selectors/TextHandler ず TextHandlers など、ほがすべおのクラスで䜿えたす。テキストノヌドを遞ばなくおも、芁玠に盎接䜿えたす。

TextHandler の説明で詳しく扱いたすが、基本的には次のように䜿いたす。

>>> page.css('.price_color')[0].re_first(r'[\d\.]+')
'51.77'

>>> page.css('.price_color').re_first(r'[\d\.]+')
'51.77'

>>> page.css('.price_color').re(r'[\d\.]+')
['51.77',
 '53.74',
 '50.10',
 '47.82',
 '54.23',
...]

>>> page.css('.product_pod h3 a::attr(href)').re(r'catalogue/(.*)/index.html')
['a-light-in-the-attic_1000',
 'tipping-the-velvet_999',
 'soumission_998',
 'sharp-objects_997',
...]

>>> filtering_function = lambda e: e.parent.tag == 'h3' and e.parent.parent.has_class('product_pod')  # As above selector
>>> page.find('a', filtering_function).attrib['href'].re(r'catalogue/(.*)/index.html')
['a-light-in-the-attic_1000']

>>> page.find_by_text('Tipping the Velvet').attrib['href'].re(r'catalogue/(.*)/index.html')
['tipping-the-velvet_999']

次のペヌゞで、TextHandler ず䞀緒にさらに詳しく説明したす。