如何使用请求上传文件

时间:2018-03-20 07:30:06

标签: python python-requests

我可以使用Selenium将文件上传为

from selenium import webdriver

driver = webdriver.Chrome()
driver.get(r'https://www.example.com')
a = driver.find_element_by_xpath("//input[@type='file']")
a.send_keys(r'C:\abc.jpg')
b =  driver.find_element_by_xpath("//output[@id='result']").text

上述代码效果很好。

现在,我想将Requests用于同一个工作。我试图在网上搜索并实现代码。但我无法得到结果。

import requests
from lxml import html

a = requests.get(r'https://www.example.com')
tree = html.fromstring(a.text)
b = tree.xpath("//input[@type='file']")
b.append(r'C:\abc.jpg')#Is it correct?

html代码如下:

<div id="test" class="abc def ghi">
    <div class="xyz def ghi">
        Drag or<br class="def ghi">Click to input file
    </div>
    <div class="pqr def ghi">
        Upload file
    </div>
    <label id="select-file" for="input" class="def ghi"></label>
    <input type="file" id="input" hidden="" class="def ghi">
</div>

代码中没有表格。如何解决问题?

1 个答案:

答案 0 :(得分:1)

您需要使用files参数。另外,表单的action属性可以指定不同的上传网址,因此最好将其检出。

以下是完整示例:

import requests
from lxml import html

host = r'https://www.example.com'
url = '/'
filename = r'C:\abc.jpg'


req = requests.get(host + url)

tree = html.fromstring(req.text)
field = tree.xpath("//input[@type='file']")
form = next(f[0].iterancestors("form"), None)
action = form.attrib['action'] if form else url

requests.post(host + action,
              files={filename: (open(filename, 'rb'), 'image/jpg')})