Python mechanize,按照url链接,nr参数是什么?

2024-07-05 14:37:06 发布

您现在位置:Python中文网/ 问答频道 /正文

很抱歉不得不问这样的问题,但是python的机械化文档似乎真的很缺乏,我无法理解。。他们只举了一个例子,我可以找到以下链接:

response1 = br.follow_link(text_regex=r"cheese\s*shop", nr=1)

但我不想使用regex,我只想根据它的url跟踪一个链接,我该怎么做。。还有什么是“nr”,有时用于以下链接?

谢谢你的消息


Tags: text文档br消息url链接linkshop
3条回答

从代码上看,我想你想

response1 = br.follow_link(link=LinkObjectToFollow)

nr与find_link调用下的文档相同。

编辑:在我的第一个粗略的一瞥,我没有意识到“链接”不是一个简单的链接。

br.follow_link接受Link对象或关键字arg(例如nr=0)。

br.links()列出所有链接。

br.links(url_regex='...')列出其url与regex匹配的所有链接。

br.links(text_regex='...')列出其链接文本与regex匹配的所有链接。

br.follow_link(nr=num)跟随页面上的第num个链接,计数从0开始。它返回一个响应对象(与br.open(…)返回的类型相同)

br.find_link(url='...')返回其url正好等于给定url的Link对象。

br.find_linkbr.linksbr.follow_linkbr.click_link都接受相同的关键字。运行help(br.find_link)查看有关这些关键字的文档。

编辑:如果您有一个要跟踪的目标url,可以执行以下操作:

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

我找到了这种方法,供不想使用regex的人参考:

r = br.open("http://www.somewebsite.com")
br.find_link(url='http://www.somewebsite.com/link1.html')
req = br.click_link(url='http://www.somewebsite.com/link1.html')
br.open(req)
print br.response().read()

或者,它也可以通过链接的文本工作:

r = br.open("http://www.somewebsite.com")
br.find_link(text='Click this link')
req = br.click_link(text='Click this link')
br.open(req)
print br.response().read()

相关问题 更多 >