如何在表单中输入数据并在python中使用cookie转到下一页

时间:2016-09-11 03:45:37

标签: python curl cookies pycurl

我想在表格中输入数据并登录网站,然后下载当前页面的来源。 通过终端的卷曲,我执行以下命令:

curl -c cookie.txt --data "email=my@email.com&pass=MyPass&submit=login" https://mywebsite.com/pageA

curl -b cookie.txt https://mywebsite.com/pageB> down.txt

我如何对pycurl做同样的事情?

1 个答案:

答案 0 :(得分:0)

docs中的示例构建:

from __future__ import print_function
import pycurl
try:
    # python 3
    from urllib.parse import urlencode
except ImportError:
    # python 2
    from urllib import urlencode

c = pycurl.Curl()
c.setopt(c.URL, 'https://mywebsite.com/pageA')

post_data = {'email': 'my@email.com', 'pass': 'MyPass', 'submit': 'login'}
# Form data must be provided already urlencoded.
postfields = urlencode(post_data)
# Sets request method to POST,
# Content-Type header to application/x-www-form-urlencoded
# and data to send in request body.
c.setopt(c.POSTFIELDS, postfields)
c.setopt(c.COOKIEJAR, 'cookie.txt')
c.setopt(c.COOKIEFILE, 'cookie.txt')

try:
    c.perform()
    c.setopt(c.URL, 'https://mywebsite.com/pageB')
    c.perform()

except pycurl.error as error:
    errno, errstr = error
    print('An error occurred: ', errstr)

c.close()