ガリガリ君のHPにある画像のsrc属性(絶対URL)を取得するために、以下のコードを書いています。
import scrapy from scrapy.spiders import CrawlSpider, Rule from scrapy.linkextractors import LinkExtractor # ガリガリ君 class AkagiSpider(CrawlSpider): name = 'akagi' allowed_domains = ['www.akagi.com'] start_urls = ( 'https://www.akagi.com/products/garigari/soda_stick.html', 'https://www.akagi.com/products/gatsun/mikan_stick.html', ) rules = ( # 辿ってほしいリンクの条件(ルール)を指定する Rule(LinkExtractor(allow=r'/garigari/.+$'), callback='parse_ice'), Rule(LinkExtractor(allow=r'/gatsun/.+$'), callback='parse_ice'), ) def parse_ice(self, response): for image_urls in response.css('article .photo figure img::attr("src")').extract(): image_url = response.urljoin(image_urls) yield{ # 商品名の要素h1の中には<span>が含まれているため、.xpath('string()')でh1以下のすべてのテキストを取得 'item_name': response.css('#contents article h1').xpath('string()').extract_first().strip(), 'image': scrapy.Request(image_url), 'price': response.css('.list_table tr td').xpath('string()').re(r'.+円'), 'amount': response.css('.list_table tr td').xpath('string()').re(r'.+ml'), 'maker': '赤城乳業', }
画像の絶対URLは取得できるのですが、取得結果のURLに余計な文字列?が入ってしまいます。以下のとおりです。
{'item_name': '大人なガリガリ君贅沢いちご(棒)', 'image': <GET https://www.akagi.com/content/images/products/200gif/otonagari_strawberry.gif>, 'price': ['100円'], 'amount': ['100ml'], 'maker': '赤城乳業'} 2018-06-03 10:25:29 [scrapy.core.scraper] DEBUG: Scraped from <200 https://www.akagi.com/products/garigari/cola_stick.html> {'item_name': 'ガリガリ君コーラ(棒)', 'image': <GET https://www.akagi.com/content/images/products/200gif/gari_cola_stick.gif>, 'price': ['70円'], 'amount': ['110ml'], 'maker': '赤城乳業'}
ご覧のとおり、'image' の値の先頭にGETが含まれてしまい、タグ<>も取得してしまいます。
最終的には
https://www.akagi.com/content/images/products/200gif/otonagari_strawberry.gif
のように、画像の絶対URLを取得したいです。
おわかりでしたら、教えてください。よろしくお願い致します。
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/06/03 02:26