我正在尝试构建一个工具来测试我的Internet连接的延迟,更具体地说是网站加载时间。 我想到了将python request模块用于加载部分。
问题是,它没有内置功能来衡量获得完整响应所花费的时间。 为此,我认为我将使用timeit
模块。
我不确定的是,如果我像这样运行timeit:
t = timeit.Timer("requests.get('http://www.google.com')", "import requests")
我实际上是在衡量响应到达所花费的时间,还是建立,发送,接收请求等所花费的时间? 我猜我可能会忽略执行时间,因为我正在测试延迟很长的网络(〜700ms)?
有没有更好的方法以编程方式执行此操作?
如何通过python模块Requests传递csrftoken? 这就是我所拥有的,但是它不起作用,并且我不确定要将其传递到哪个参数(数据,标头,身份验证...)
import requests
from bs4 import BeautifulSoup
URL = 'https://portal.bitcasa.com/login'
client = requests.session(config={'verbose': sys.stderr})
# Retrieve the CSRF token first
soup = BeautifulSoup(client.get('https://portal.bitcasa.com/login').content)
csrftoken = soup.find('input', dict(name='csrfmiddlewaretoken'))['value']
login_data = dict(username=EMAIL, password=PASSWORD, csrfmiddlewaretoken=csrftoken)
r = client.post(URL, data=login_data, headers={"Referer": "foo"})
每次都有相同的错误消息。
<h1>Forbidden <span>(403)</span></h1>
<p>CSRF verification failed. Request aborted.</p>
def request():
#encoded_xml = urllib.urlencode({'XML': read_xml()})
#encoded_xml = read_xml()
headers = {'Authorization': AUTH_TOKEN,\
'developerToken': DEVELOPER_TOKEN,\
'clientCostumerID': CLIENT_ID}
content = {'__rdxml': encoded_xml}
#content = encoded_xml
#content = {'__rdxml': read_xml2()}
r = requests.post(URL, data=content,\
headers=headers)
return r
这些组合似乎无效。
标头由于某种原因未设置。
我需要解析一个站点,但出现错误403 Forbidden。这是一个代码:
url = 'http://worldagnetwork.com/'
result = requests.get(url)
print(result.content.decode())
其输出:
<html>
<head><title>403 Forbidden</title></head>
<body bgcolor="white">
<center><h1>403 Forbidden</h1></center>
<hr><center>nginx</center>
</body>
</html>
请说出问题所在。
我有两个Python脚本。 一种使用Urllib2库,另一种使用请求库。
我发现请求更容易实现,但找不到urlib2的print post_call.text
函数的等效项。 例如:
...
response = url.urlopen(req)
print response.geturl()
print response.getcode()
data = response.read()
print data
建立好我的发布网址后,print post_call.text
会给我内容-我正尝试连接到vcloud Director api实例,并且响应显示我可以访问的端点。 但是,如果我按以下方式使用请求库....
....
def post_call(username, org, password, key, secret):
endpoint = '<URL ENDPOINT>'
post_url = endpoint + 'sessions'
get_url = endpoint + 'org'
headers = {'Accept':'application/*+xml;version=5.1', \
'Authorization':'Basic '+ base64.b64encode(username + "@" + org + ":" + password), \
'x-id-sec':base64.b64encode(key + ":" + secret)}
print headers
post_call = requests.post(post_url, data=None, headers = headers)
print post_call, "POST call"
print post_call.text, "TEXT"
print post_call.content, "CONTENT"
post_call.status_code, "STATUS CODE"
....
....即使在请求后调用中状态代码等于200,print post_call.text
和print post_call.content
也不会返回任何内容。
为什么我的请求响应不返回任何文本或内容?
我正在尝试使用requests.post将请求数组(列表)发送到WheniWork API,并且不断出现两个错误之一。 当我将列表作为列表发送时,出现拆包错误,当我将其作为字符串发送时,出现错误要求我提交数组。 我认为这与请求如何处理列表有关。 以下是示例:
url='https://api.wheniwork.com/2/batch'
headers={"W-Token": "Ilovemyboss"}
data=[{'url': '/rest/shifts', 'params': {'user_id': 0,'other_stuff':'value'}, 'method':'post',{'url': '/rest/shifts', 'params': {'user_id': 1,'other_stuff':'value'}, 'method':'post'}]
r = requests.post(url, headers=headers,data=data)
print r.text
# ValueError: too many values to unpack
只需将数据的值包装在引号中:
url='https://api.wheniwork.com/2/batch'
headers={"W-Token": "Ilovemyboss"}
data="[]" #removed the data here to emphasize that the only change is the quotes
r = requests.post(url, headers=headers,data=data)
print r.text
#{"error":"Please include an array of requests to make.","code":5000}
环境:Python 3.6.3要求2.18.4PyCharm 2018.1
在正常运行中使用上述配置时,一切都很好。 但是,当使用PyCharm调试器时,我的输出不断给我两种异常:
Exception ignored in: <generator object urlsplit.<locals>.<genexpr> at 0x7f69803940a0>
Traceback (most recent call last):
File "/usr/lib/python3.6/urllib/parse.py", line 433, in <genexpr>
if not rest or any(c not in '0123456789' for c in rest):
要么
SystemError: error return without exception set
Exception ignored in: <generator object iter_slices at 0x7f69803940f8>
Traceback (most recent call last):
File "/home/damian/workspace/DofusV2/venv/lib/python3.6/site-packages/requests/utils.py", line 449, in iter_slices
def iter_slices(string, slice_length):
`
在单个项目中这不是问题,我在无数次的多个项目中都遇到过这个问题。 但是,每个项目都是多线程的(我不知道这有什么区别)问题是,当不使用调试器时,我没有这个问题,而且它对应用程序的稳定和运行没有任何作用。 我的问题是为什么会发生这种情况,我至少可以抑制它,以免污染我的日志吗?
我想通过内部公司链接向服务器发出请求时忽略certification validation
。
使用python requests
库,我会这样做:
r = requests.get(link, allow_redirects=False,verify=False)
如何使用urllib2库做同样的事情?
import requests
data = {'foo':'bar'}
url = 'https://foo.com/bar'
r = requests.post(url, data=data)
如果URL使用自签名证书,则失败并显示
requests.exceptions.SSLError: [Errno 1] _ssl.c:507: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed
我知道我可以将False
传递给verify
参数,如下所示:
r = requests.post(url, data=data, verify=False)
但是,我想做的是将请求指向磁盘上的公共密钥副本,并告诉它信任该证书。
我正在学习Django 1.6。
我想使用HTTP POST请求发布一些JSON,并且我正在使用Django完成此任务的学习。
我尝试使用request.POST['data']
、r.text
、request.body
,但没有一个对我有用。
我的views.py是
import json
from django.http import StreamingHttpResponse
def main_page(request):
if request.method=='POST':
received_json_data=json.loads(request.POST['data'])
#received_json_data=json.loads(request.body)
return StreamingHttpResponse('it was post request: '+str(received_json_data))
return StreamingHttpResponse('it was GET request')
我正在使用请求模块发布JSON数据。
import requests
import json
url = "http://localhost:8000"
data = {'data':[{'key1':'val1'}, {'key2':'val2'}]}
headers = {'content-type': 'application/json'}
r=requests.post(url, data=json.dumps(data), headers=headers)
r.text
r.text
应该打印该消息并发布数据,但我无法解决此简单问题。 请告诉我如何在Django 1.6中收集发布的数据?
在HTTP协议中,您可以使用keep-alive在一个套接字中发送许多请求,然后立即接收来自服务器的响应,这样可以大大加快整个过程。 有什么办法可以在python请求库中做到这一点吗? 还是有其他方法可以使用请求库来加快速度?
我正在尝试导入requests
模块,但出现此错误我的python版本是3.4在ubuntu 14.04上运行
>>> import requests
Traceback (most recent call last):
File "/usr/local/lib/python3.4/dist-packages/requests/packages/urllib3/connectionpool.py", line 10, in <module>
from queue import LifoQueue, Empty, Full
ImportError: cannot import name 'LifoQueue'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.4/dist-packages/requests/__init__.py", line 58, in <module>
from . import utils
File "/usr/local/lib/python3.4/dist-packages/requests/utils.py", line 26, in <module>
from .compat import parse_http_list as _parse_list_header
File "/usr/local/lib/python3.4/dist-packages/requests/compat.py", line 7, in <module>
from .packages import chardet
File "/usr/local/lib/python3.4/dist-packages/requests/packages/__init__.py", line 3, in <module>
from . import urllib3
File "/usr/local/lib/python3.4/dist-packages/requests/packages/urllib3/__init__.py", line 10, in <module>
from .connectionpool import (
File "/usr/local/lib/python3.4/dist-packages/requests/packages/urllib3/connectionpool.py", line 12, in <module>
from Queue import LifoQueue, Empty, Full
ImportError: No module named 'Queue'
我正在尝试使用Python中的“请求”模块发布一个登录网站的请求,但它实际上无法正常工作。 我是新来的...所以我不知道是否应该使用我的用户名和密码cookie或某种我发现的HTTP授权类型(??)。
from pyquery import PyQuery
import requests
url = 'http://www.locationary.com/home/index2.jsp'
所以现在,我认为我应该使用“发布”和cookie。
ck = {'inUserName': 'USERNAME/EMAIL', 'inUserPass': 'PASSWORD'}
r = requests.post(url, cookies=ck)
content = r.text
q = PyQuery(content)
title = q("title").text()
print title
我有种感觉,我在做饼干的事情做错了...我不知道。
如果登录不正确,则首页标题应显示在“ Locationary.com”上;如果登录不正确,则应显示为“首页”。
如果您可以向我解释一些有关请求和cookie的事情,并帮助我解决这个问题,我将不胜感激。:d
谢谢。
...它仍然没有真正起作用。 好的...所以这是登录之前主页HTML的内容:
</td><td><img src="http://www.locationary.com/img/LocationaryImgs/icons/txt_email.gif"> </td>
<td><input class="Data_Entry_Field_Login" type="text" name="inUserName" id="inUserName" size="25"></td>
<td><img src="http://www.locationary.com/img/LocationaryImgs/icons/txt_password.gif"> </td>
<td><input class="Data_Entry_Field_Login" type="password" name="inUserPass" id="inUserPass"></td>
所以我认为我做对了,但输出仍然是“ Locationary.com”
第二次编辑:
我希望能够长时间保持登录状态,并且每当我请求该域下的页面时,我都希望内容显示出来就像我已登录一样。
在我的脚本中,get
永远不会返回:
import requests
print ("requesting..")
# This call never returns!
r = requests.get(
"http://www.justdial.com",
proxies = {'http': '222.255.169.74:8080'},
)
print(r.ok)
可能是什么原因? 有补救办法吗? get
使用的默认超时是多少?
我正在尝试使用Requests库发送带有后期处理请求的cookie,但是我不确定如何根据其文档实际设置cookie。 该脚本可在Wikipedia上使用,并且需要发送的cookie具有以下形式:
enwiki_session=17ab96bd8ffbe8ca58a78657a918558e; path=/; domain=.wikipedia.com; HttpOnly
但是,requests
文档快速入门给出了以下示例:
cookies = dict(cookies_are='working')
如何使用该库对上述Cookie进行编码? 我是否需要使用python的标准cookie库进行制作,然后将其与POST请求一起发送?
我想从以下网站获取内容。 如果我使用像Firefox或Chrome这样的浏览器,我可以获得我想要的真实网站页面,但如果我使用Python请求包(或wget
命令)来获取它,它将返回一个完全不同的HTML页面。 我认为网站的开发者为此做了一些块,所以问题是:
如何使用python请求或命令wget伪造浏览器访问?
[http://www.ichangtou.com/#company:data_000008.html]
我正在使用极好的Python Requests库。 我注意到,精美的文档中有许多如何在不解释原因的情况下做某事的例子。 例如,non-text responses
和non-text requests
都显示为如何获取服务器响应的示例。 但它在哪里解释了这些属性的作用? 例如,我何时会选择一个而不是另一个? 我看到thar r.text
有时会返回一个unicode对象,我想非文本响应会有所不同。 但所有这些记录在哪里? 请注意,链接的文档确实说明:
对于非文本请求,您还可以以字节为单位访问响应正文:
但接下来它将展示文本响应的示例! 我只能假设上面的引用意味着说non-text responses
而不是non-text requests
,因为非文本请求在HTTP中没有意义。
简而言之,与Python请求站点上的(优秀)教程相比,库的正确文档在哪里?
我非常喜欢requests
软件包及其处理JSON响应的舒适方式。
不幸的是,我不明白我是否也可以处理XML响应。 有没有人体验过如何使用requests
软件包处理XML响应? 是否有必要包含另一个XML解码包?
我想在asyncio
中执行并行的http请求任务,但我发现python-requests
会阻止asyncio
的事件循环。我发现了aiohttp但它无法使用http代理提供http请求服务。
所以我想知道是否有办法在asyncio
的帮助下进行异步http请求。