用Mechanize搜索Pastbin.com

0 投票
2 回答
972 浏览
提问于 2025-04-19 10:59

我借用的这段代码在Google.com上运行得很好,但在pastebin.com上却不行。我希望能得到一些建议,为什么我无法在pastebin.com上进行搜索。

import re
from mechanize import Browser
br = Browser()

# Ignore robots.txt
br.set_handle_robots( False )
# user-agent that isn't a robot
br.addheaders = [('User-agent', 'Firefox')]

# Retrieve the web page
br.open( "http://pastebin.com" )

# Select the search box and search for 'foo'
br.select_form( 'f' )
br.form[ 'q' ] = 'facebook'

# Get the search results
br.submit()

# Find the link
resp = None
for link in br.links():
    siteMatch = re.compile( 'www.facebook.com' ).search( link.url )
    if siteMatch:
        resp = br.follow_link( link )
        break

# Print the site
content = resp.get_data()
print content

2 个回答

0
br.select_form( 'f' )
br.form[ 'q' ] = 'facebook'

在Pastebin的主页上,没有叫做“f”的表单。你可以查看页面的源代码,找到正确的名称。

0

你所描述的问题可以通过提供一个有效的表单名称来解决:

br.select_form(name='search_form')

不过,之后在尝试获取结果时,你可能会遇到其他问题——这属于另一个问题的范畴。

撰写回答