机械化开放网址python [英] mechanize open Url python
本文介绍了机械化开放网址python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用python中的机械化打开URL.该代码执行没有错误,但实际上没有任何反应.我想念什么?另外,有没有办法设置浏览器?这是python 2.7.
I am trying to open a URL using mechanize in python. The code executes with no errors, but nothing actually happens. What am I missing? Also, is there a way to set the browser? This is python 2.7.
import mechanize
url='http://www.google.com/'
op = mechanize.Browser() # use mecahnize's browser
op.set_handle_robots(False) #tell the webpage you're not a robot
op.open(url)
推荐答案
mechanize
不使用真实的浏览器-它是用于程序化Web浏览的工具.
mechanize
doesn't use real browsers - it is a tool for programmatic web-browsing.
例如,打开URL后打印出页面标题:
For example, print out the page title after opening the url:
>>> import mechanize
>>> url='http://www.google.com/'
>>> op = mechanize.Browser()
>>> op.set_handle_robots(False)
>>> op.open(url)
<response_seek_wrapper at 0x10247ebd8 whose wrapped object = <closeable_response at 0x102479a70 whose fp = <socket._fileobject object at 0x101903950>>>
>>> op.title()
'Google'
以下是如何提交Google搜索表单的后续操作:
Here's a follow up, how you can submit the Google search form:
import mechanize
url='http://www.google.com/'
op = mechanize.Browser()
op.set_handle_equiv(True)
op.set_handle_gzip(True)
op.set_handle_redirect(True)
op.set_handle_referer(True)
op.set_handle_robots(False)
# pretend you are a real browser
op.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')]
op.open(url)
op.select_form(nr=1)
op.form['q'] = 'Does mechanize use a real browser?'
op.submit()
print op.geturl()
打印:
http://www.google.com/search?hl=en&source=hp&q=Does+mechanize+use+a+real+browser%3F&btnG=Google+Search&gbv=1
这篇关于机械化开放网址python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文