Merge pull request #7 from Kanezoh/add_page_links

Add page links
master
Kanezoh 2021-08-21 20:01:59 +09:00 committed by GitHub
commit f0889b8b64
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 83 additions and 0 deletions

25
spec/page/link_spec.cr Normal file
View File

@ -0,0 +1,25 @@
require "../spec_helper"
describe "Mechanize Page Link test" do
it "returns href" do
agent = Mechanize.new
page = agent.get("http://example.com/link")
link = page.links.first
link.href.should eq "http://example.com/"
end
it "returns text" do
agent = Mechanize.new
page = agent.get("http://example.com/link")
link = page.links.first
link.text.should eq "link text"
end
it "is clickable and returns page" do
agent = Mechanize.new
page = agent.get("http://example.com/link")
link = page.links.first
page = link.click
page.uri.to_s.should eq "http://example.com/"
end
end

View File

@ -45,4 +45,10 @@ describe "Mechanize Page test" do
form = page.form_with({name: "sample_form"})
form.name.should eq "sample_form"
end
it "return page links, links means <a> and <area>" do
agent = Mechanize.new
page = agent.get("http://example.com/link")
page.links.size.should eq 2
end
end

View File

@ -22,6 +22,23 @@ WebMock.stub(:get, "example.com/form").to_return(body: <<-BODY
</html>
BODY
)
WebMock.stub(:get, "example.com/link").to_return(body: <<-BODY
<html>
<head>
<title>page_title</title>
</head>
<body>
<a href="http://example.com/">link text</a>
<map>
<area shape="rect" coords="184,6,253,27"
href="http://example.com" />
</map>
</body>
</html>
BODY
)
WebMock.stub(:post, "example.com/post_path")
.with(body: "name=foo&email=bar", headers: {"Content-Type" => "application/x-www-form-urlencoded"})
.to_return(body: "success")

View File

@ -113,4 +113,10 @@ class Mechanize
def max_history=(length)
history.max_size = length
end
# click link, and return page.
def click(link)
href = link.href
get href
end
end

View File

@ -1,5 +1,6 @@
require "./file"
require "./utils/element_matcher"
require "./page/link"
class MechanizeCr::Page < MechanizeCr::File
include MechanzeCr::ElementMatcher
@ -33,6 +34,14 @@ class MechanizeCr::Page < MechanizeCr::File
end.to_a
end
def links
links = %w{a area}.map do |tag|
css(tag).map do |node|
PageContent::Link.new(node, @mech, self)
end
end.flatten
end
# generate form_with, forms_with methods
# ex) form_with({:name => "login_form"})
# it detects form(s) which match conditions.

View File

@ -0,0 +1,20 @@
class MechanizeCr::PageContent::Link
getter node : Lexbor::Node
getter page : Page
getter mech : Mechanize
getter href : String
getter text : String
def initialize(node, mech, page)
@node = node
@page = page
@mech = mech
@href = node.fetch("href", "")
@text = node.inner_text
end
# click on this link
def click
@mech.click self
end
end