使用python提交到Web表单 [英] Submitting to a web form using python
问题描述
我看过很多次这样的问题,但没有帮助
I have seen questions like this asked many many times but none are helpful
我正在尝试将数据提交到网络上已尝试的请求中的表单,而urllib却没有任何作用
Im trying to submit data to a form on the web ive tried requests, and urllib and none have worked
例如,下面的代码应在SO上搜索[python]标记:
for example here is code that should search for the [python] tag on SO:
import urllib
import urllib2
url = 'http://stackoverflow.com/'
# Prepare the data
values = {'q' : '[python]'}
data = urllib.urlencode(values)
# Send HTTP POST request
req = urllib2.Request(url, data)
response = urllib2.urlopen(req)
html = response.read()
# Print the result
print html
但是,当我运行它时,我会得到主页的html信息
yet when i run it i get the html soure of the home page
这是使用请求的示例:
import requests
data= {
'q': '[python]'
}
r = requests.get('http://stackoverflow.com', data=data)
print r.text
相同的结果!我不明白为什么这些方法无法奏效,但我已经在各种站点上尝试了这些方法,但均未成功,因此,如果有人成功完成此操作,请告诉我如何做!
same result! i dont understand why these methods arent working i've tried them on various sites with no success so if anyone has successfully done this please show me how!
非常感谢!
推荐答案
如果您要使用requests
,请使用params
参数,而不要使用data
(请参见
If you want to pass q
as a parameter in the URL using requests
, use the params
argument, not data
(see Passing Parameters In URLs):
r = requests.get('http://stackoverflow.com', params=data)
这将请求 https://stackoverflow.com/?q=%5Bpython%5D ,不是您要找的东西.
This will request https://stackoverflow.com/?q=%5Bpython%5D , which isn't what you are looking for.
您真的想 POST
为表格.试试这个:
You really want to POST
to a form. Try this:
r = requests.post('https://stackoverflow.com/search', data=data)
这与 GET
-ting https://stackoverflow.com/questions基本相同/tagged/python ,但我想您会从中得到灵感的.
This is essentially the same as GET
-ting https://stackoverflow.com/questions/tagged/python , but I think you'll get the idea from this.
这篇关于使用python提交到Web表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!