“post” method to communicate directly with a serve

2019-06-12 17:20发布

Just started with python not long ago, and I'm learning to use "post" method to communicate directly with a server. A fun script I'm working on right now is to post comments on wordpress. The script does post comments on my local site, but I don't know why it raises HTTP Error 404 which means page not found. Here's my code, please help me find what's wrong:

import urllib2
import urllib

url='http://localhost/wp-comments-post.php'
user_agent='Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'  
values={'author':'Urllib Test', 'email':'test@test.com',  'url':'', 'comment':'This is a test comment from python', 'submit':'Post Comment', 'comment_post_ID': '1', 'comment_parent':'0'}  
headers={'User-Agent': user_agent}

data=urllib.urlencode(values)  
req=urllib2.Request(url, data, headers)

urllib2.urlopen(req)

2条回答
劫难
2楼-- · 2019-06-12 17:28

I recommend you to use Mechanize. It will simplify your life.

查看更多
放荡不羁爱自由
3楼-- · 2019-06-12 17:40

why is there a 'url' in your values ? did you try without it ?

then, try replacing localhost with 127.0.0.1 (if localhost is not in your hosts file). Are you on windows or linux ?

查看更多
登录 后发表回答