Last active
June 25, 2019 07:53
-
-
Save iansrc0811/fcf62a3640537c21afac2a37c24d7ba5 to your computer and use it in GitHub Desktop.
爬博客來書名的爬蟲
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'rubygems' | |
require 'nokogiri' | |
require 'mechanize' | |
require 'open-uri' | |
class Books_Crawler | |
def get_book_names(book_name) | |
book_item = self.start_crawler(book_name) | |
book_names = [] | |
book_item.each do |name| | |
book_names.push(name['title']) | |
end | |
return book_names | |
end | |
def get_book_links(book_name) | |
book_item = self.start_crawler(book_name) | |
book_links = [] | |
book_item.each do |name| | |
book_links.push(name['href']) | |
end | |
return book_links | |
end | |
def start_crawler(book_name) | |
agent = Mechanize.new | |
books_url = "http://www.books.com.tw/" | |
page = agent.get(books_url) | |
books_form = page.form('search') | |
books_form.key = book_name | |
page = agent.submit(books_form) | |
current_url = page.uri.to_s | |
page = Nokogiri::HTML(open(current_url)) | |
book_list = [] | |
book_item = page.xpath("//li[@class='item']/a[@rel='mid_image']") | |
return book_item | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
模擬在博客來(http://www.books.com.tw/) 搜尋的結果,需要給一個搜尋字串,爬蟲回傳搜尋結果的第一頁的書名或書的連結。此例為搜尋"ruby"並獲取書名
Usage :