質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
スクレイピング

スクレイピングとは、公開されているWebサイトからページ内の情報を抽出する技術です。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

Scrapy

Scrapyは、Pythonで開発されたオープンソースソフトウェアです。スクレイピングという、Webサービスから必要な情報を取り出したり自動操作をしたりする技術を使うものです。

Q&A

解決済

1回答

1494閲覧

Scrapy、for文内で指定した複数リンク先から特定の値を取得しCSV出力したい

fukazume

総合スコア78

スクレイピング

スクレイピングとは、公開されているWebサイトからページ内の情報を抽出する技術です。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

Scrapy

Scrapyは、Pythonで開発されたオープンソースソフトウェアです。スクレイピングという、Webサービスから必要な情報を取り出したり自動操作をしたりする技術を使うものです。

0グッド

2クリップ

投稿2019/10/25 05:21

編集2019/10/25 05:22

##■やりたいこと
こちらのデモサイト(http://books.toscrape.com/)の書籍一覧ページと個別詳細ページから、それぞれ情報を抽出して以下のような一つのCSVファイルにまとめて出力しようと試みています。※個別ページ(②)からも書籍タイトルやURLを抽出できますが、ここではそれらを一覧ページ(①)から抽出する前提で考えています。

以下に、記述途中のコードがあります。scrapy.Requestのfor文、yieldの行をコメントアウトすると一覧ページからitemは抽出できる状態ですが、個別詳細ページのdescriptionは抽出できていません。この未完成コードを意図した動作をするように修正する方法をご教示いただきたいです。どうぞ宜しくお願い申し上げます。

#####<CSV出力イメージ、構成>

書籍タイトル(①)書籍の個別詳細URL(①)概要(②)
A Light in the Attichttp://books.toscrape.com/catalogue/a-light-in-the-attic_1000/index.htmlIt's hard to imagine a world without A Light in the Attic. This now-classic collection of poetry and (中略) ...more
Tipping the Velvethttp://books.toscrape.com/catalogue/tipping-the-velvet_999/index.html"Erotic and absorbing...Written with starling power."(中略) ...more
(リスト項目数分つづく)(リスト項目数分つづく)(リスト項目数分つづく)

①一覧ページ(http://books.toscrape.com/)から抽出
②個別ページ(http://books.toscrape.com/catalogue/a-light-in-the-attic_1000/index.html 等)から抽出

#####<一覧ページからの抽出箇所(赤枠)>
http://books.toscrape.com/
一覧
#####<個別ページからの抽出箇所(赤枠)>
http://books.toscrape.com/catalogue/a-light-in-the-attic_1000/index.html
イメージ説明

##■現状

Python

1# -*- coding: utf-8 -*- 2#注意: 現状で一部正常に動作しないコードです。 3import scrapy 4from ..items import BooksItem 5 6class BooksSpider(scrapy.Spider): 7 name = "books" 8 allowed_domains = ["books.toscrape.com"] 9 start_urls = [ 10 'http://books.toscrape.com/', 11 ] 12 def parse(self, response): 13 list_rows = response.xpath('//*[@id="default"]/div/div/div/div/section/div[2]/ol/li') 14 for list_row in list_rows: 15 # ↓一覧ページから書籍タイトル、書籍の個別詳細URLを抽出 16 item = BooksItem() 17 item['book_title'] = list_row.xpath('/article/h3/a/@title').extract_first() 18 item['book_url'] = list_row.xpath('article/div[1]/a/@href').extract_first() 19 # ↓個別ページから概要を抽出(現状正常に動作せず) 20 for book_url in response.css("article.product_pod > h3 > a ::attr(href)").extract(): 21 yield scrapy.Request(response.urljoin(book_url), callback=self.parse_book_page) 22 yield item 23 24 def parse_book_page(self, response): 25 item = BooksItem() 26 product = response.css("div.product_main") 27 item['description'] = response.xpath("//div[@id='product_description']/following-sibling::p/text()").extract_first() 28 yield item

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

ベストアンサー

必要な情報をmetaで渡します。
https://docs.scrapy.org/en/latest/topics/request-response.html#scrapy.http.Request.meta

This dict is shallow copied when the request is cloned using the copy() or replace() methods, and can also be accessed, in your spider, from the response.meta attribute.

https://docs.scrapy.org/en/latest/topics/request-response.html#scrapy.http.Response.meta

A shortcut to the Request.meta attribute of the Response.request object (ie. self.request.meta).


python

1 def parse(self, response): 2 list_rows = response.xpath('//*[@id="default"]/div/div/div/div/section/div[2]/ol/li') 3 for list_row in list_rows: 4 # ↓一覧ページから書籍タイトル、書籍の個別詳細URLを抽出 5 book_title = list_row.xpath('/article/h3/a/@title').extract_first() 6 book_url = list_row.xpath('article/div[1]/a/@href').extract_first() 7 # ↓個別ページから概要を抽出(現状正常に動作せず) 8 for book_url in response.css("article.product_pod > h3 > a ::attr(href)").extract(): 9 item = BooksItem() 10 item['book_title'] = book_title 11 item['book_url'] = book_url 12 yield scrapy.Request(response.urljoin(book_url), 13 callback=self.parse_book_page, 14 meta={'item': item}) 15 16 def parse_book_page(self, response): 17 # requestでmetaにセットされたitemを取り出す 18 item = response.meta['item'] 19 product = response.css("div.product_main") 20 item['description'] = response.xpath("//div[@id='product_description']/following-sibling::p/text()").extract_first() 21 yield item

動作の確認まではしませんが。

投稿2019/10/25 11:47

quickquip

総合スコア11038

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

fukazume

2019/10/26 10:47

metaでメソッド間で値を渡す方法を存じ上げませんでした。わかりやすいサンプルコードと引用で理解が進みました。以前にもお世話になりましたが今回も大変ありがとうございます!
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問