【问题标题】:How to upload file using Requests如何使用请求上传文件
【发布时间】:2018-08-28 22:23:18
【问题描述】:

我可以使用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>

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

【问题讨论】:

  • this answer 可能会有所帮助。你需要requests.post你的(编码的)图像。
  • 发送任何类型的数据到服务器,你应该使用'post'函数。 docs.python-requests.org/en/master/user/quickstart/…
  • 示例写道:requests.post(url, params=params, data=json.dumps(data), headers=headers)data = {"eventType": "AAS_PORTAL_START", "data": {"uid": "hfe3hf45huf33545", "aid": "1", "vid": "1"}}。但在我的情况下,我不知道如何传入所需的字典。是data={"//input[@type='file']": r'C:\abc.jpg' }吗?
  • 有人可以帮忙吗?
  • 假设你想post a file,试试这样的:requests.post('https://www.example.com', files={b.attrib['name']: open(r'C:\abc.jpg', 'rb')})

标签: python python-requests


【解决方案1】:

您需要使用files 参数。另外form的action属性可以指定不同的上传url,最好查看一下。

这里是完整的例子:

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')})

【讨论】:

  • 谢谢你,尼基塔。我试图运行你的代码。但是,我得到了错误:form = list(f[0].iterancestors("form"))[0] IndexError: list index out of range 因为ist(f[0].iterancestors("form")) 等于[]
  • 我已经包含了 html。有什么建议吗?
  • 嗨,陈。没有表格的情况并不常见。应该有一些脚本处理该字段。无论如何,我已经编辑了我的答案以更准确地解决您的问题
猜你喜欢
  • 2014-04-29
  • 1970-01-01
  • 2021-09-03
  • 2021-09-19
  • 2011-08-30
相关资源
最近更新 更多