问题
I want to scrape a page like - I'm using scrapy and python for the same...
I want to scrape the button which you can see in the below pic (left pic)
http://postimg.org/image/syhauheo7/
When I click the button in green saying View Code, It does three things:
- Redirect to another id.
- Opens a popup containing
code - Show the
codeon the same page as can be seen in the above pic on right
How can I scrape the code using scrapy and python framework?
回答1:
Here's your spider:
from scrapy.http import Request
from scrapy.item import Item, Field
from scrapy.selector import HtmlXPathSelector
from scrapy.spider import BaseSpider
class VoucherItem(Item):
voucher_id = Field()
code = Field()
class CuponationSpider(BaseSpider):
name = "cuponation"
allowed_domains = ["cuponation.in"]
start_urls = ["https://www.cuponation.in/babyoye-coupons"]
def parse(self, response):
hxs = HtmlXPathSelector(response)
crawled_items = hxs.select('//div[@class="six columns voucher-btn"]/a')
for button in crawled_items:
voucher_id = button.select('@data-voucher-id').extract()[0]
item = VoucherItem()
item['voucher_id'] = voucher_id
request = Request("https://www.cuponation.in/clickout/index/id/%s" % voucher_id,
callback=self.parse_code,
meta={'item': item})
yield request
def parse_code(self, response):
hxs = HtmlXPathSelector(response)
item = response.meta['item']
item['code'] = hxs.select('//div[@class="code-field"]/span/text()').extract()
return item
If you run it via:
scrapy runspider <script_name.py> --output output.json
you'll see the following in the output.json:
{"voucher_id": "5735", "code": ["MUM10"]}
{"voucher_id": "3634", "code": ["Deal Activated. Enjoy Shopping"]}
{"voucher_id": "5446", "code": ["APP20"]}
{"voucher_id": "5558", "code": ["No code for this deal"]}
{"voucher_id": "1673", "code": ["Deal Activated. Enjoy Shopping"]}
{"voucher_id": "3963", "code": ["CNATION150"]}
{"voucher_id": "5515", "code": ["Deal Activated. Enjoy Shopping"]}
{"voucher_id": "4313", "code": ["Deal Activated. Enjoy Shopping"]}
{"voucher_id": "4309", "code": ["Deal Activated. Enjoy Shopping"]}
{"voucher_id": "1540", "code": ["Deal Activated. Enjoy Shopping"]}
{"voucher_id": "4310", "code": ["Deal Activated. Enjoy Shopping"]}
{"voucher_id": "1539", "code": ["Deal Activated. Enjoy Shopping"]}
{"voucher_id": "4312", "code": ["Deal Activated. Enjoy Shopping"]}
{"voucher_id": "4311", "code": ["Deal Activated. Enjoy Shopping"]}
{"voucher_id": "2785", "code": ["Deal Activated. Enjoy Shopping"]}
{"voucher_id": "3631", "code": ["Deal Activated. Enjoy Shopping"]}
{"voucher_id": "4496", "code": ["Deal Activated. Enjoy Shopping"]}
Happy crawling!
来源:https://stackoverflow.com/questions/16499161/how-to-scrape-coupon-code-of-coupon-site-coupon-code-comes-on-clicking-button