我正在尝试使用 urllib 库编写一个python脚本,该库自动填写网站的表单,然后发送邮件。
我知道这一点,因为网站也是我早就完成的。
import urllib.request
import urllib.parse
url = "http://saeindiauvce.com/"
values ={'name':'bibhash1970' ,
'to':'bibhash1996@gmail.com' ,
'subject':'just checking' ,
'message':'scraping1234' ,
'submit':'save'}
#print (values)
data = urllib.parse.urlencode(values)
data = data.encode('utf-8')
req = urllib.request.Request(url,data)
resp = urllib.request.urlopen(req)
respdata = resp.read()
print (respdata)
POST请求无效,我不知道出了什么问题。
答案 0 :(得分:0)
您显示的页面中的表单如下:
<form action="mail.php" method="POST" class="form-horizontal" role="form">
<!--...-->
</form>
因此,您应该将请求发送到mail.php
而不是索引。
import urllib.request
import urllib.parse
url = "http://saeindiauvce.com/mail.php"
values ={'name':'bibhash1970' ,
'to':'bibhash1996@gmail.com' ,
'subject':'just checking' ,
'message':'scraping1234' ,
'submit':'save'}
#print (values)
data = urllib.parse.urlencode(values)
data = data.encode('utf-8')
req = urllib.request.Request(url,data)
urllib.request.urlopen(req)
运行时,我收到303错误,但在Firefox浏览器中运行时会出现同样的错误:
使用网络管理员时。
shell中的演示:
$ python3
Python 3.5.2 (default, Nov 17 2016, 17:05:23)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> import urllib.request
>>> import urllib.parse
>>> url = "http://saeindiauvce.com/mail.php"
>>> values ={'name':'bibhash1970' ,
... 'to':'bibhash1996@gmail.com' ,
... 'subject':'just checking' ,
... 'message':'this is a test' ,
... 'submit':'save'}
>>> #print (values)
...
>>> data = urllib.parse.urlencode(values)
>>> data = data.encode('utf-8')
>>> req = urllib.request.Request(url,data)
>>> resp = urllib.request.urlopen(req)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.5/urllib/request.py", line 163, in urlopen
return opener.open(url, data, timeout)
File "/usr/lib/python3.5/urllib/request.py", line 472, in open
response = meth(req, response)
File "/usr/lib/python3.5/urllib/request.py", line 582, in http_response
'http', request, response, code, msg, hdrs)
File "/usr/lib/python3.5/urllib/request.py", line 510, in error
return self._call_chain(*args)
File "/usr/lib/python3.5/urllib/request.py", line 444, in _call_chain
result = func(*args)
File "/usr/lib/python3.5/urllib/request.py", line 590, in http_error_default
raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 303: See Other