br.follow_link
takes either a Link
object or a keyword arg (such as nr=0
).
br.links()
lists all the links.
br.links(url_regex='...')
lists all the links whose urls matches the regex.
br.links(text_regex='...')
lists all the links whose link text matches the regex.
br.follow_link(nr=num)
follows the num
th link on the page, with counting starting at 0. It returns a response object (the same kind what br.open(...) returns)
br.find_link(url='...')
returns the Link
object whose url
exactly equals the given url.
br.find_link
, br.links
, br.follow_link
, br.click_link
all accept the same keywords. Run help(br.find_link)
to see documentation on those keywords.
Edit: If you have a target url that you wish to follow, you could do something like this:
import mechanize
br = mechanize.Browser()
response=br.open("http://www.example.com/")
target_url='http://www.rfc-editor.org/rfc/rfc2606.txt'
for link in br.links():
print(link)
# Link(base_url='http://www.example.com/', url='http://www.rfc-editor.org/rfc/rfc2606.txt', text='RFC 2606', tag='a', attrs=[('href', 'http://www.rfc-editor.org/rfc/rfc2606.txt')])
print(link.url)
# http://www.rfc-editor.org/rfc/rfc2606.txt
if link.url == target_url:
print('match found')
# match found
break
br.follow_link(link) # link still holds the last value it had in the loop
print(br.geturl())
# http://www.rfc-editor.org/rfc/rfc2606.txt