Python-эквивалент `curl -v http://example.com/` - PullRequest
0 голосов
/ 21 января 2019

Я экспериментировал с различными модулями Python, такими как pycurl и requests, но все еще не смог получить curl -v <URL> вывод, как показано ниже.

DESIRED OUTPUT (в коде Python)

C:\>curl -v http://example.com/
*   Trying 93.184.216.34...
* TCP_NODELAY set
* Connected to example.com (93.184.216.34) port 80 (#0)
> GET / HTTP/1.1
> Host: example.com
> User-Agent: curl/7.52.1
> Accept: */*
>
< HTTP/1.1 200 OK
< Cache-Control: max-age=604800
< Content-Type: text/html; charset=UTF-8
< Date: Mon, 21 Jan 2019 00:34:32 GMT
< Etag: "1337+ident"
< Expires: Mon, 28 Jan 2019 00:34:32 GMT
< Last-Modified: Fri, 09 Aug 2013 23:54:35 GMT
< Server: ECS (sjc/4E29)
< Vary: Accept-Encoding
< X-Cache: HIT
< Content-Length: 1270
<
<!doctype html>
<html>
... input truncated ...
</html>
* Curl_http_done: called premature == 0
* Connection #0 to host example.com left intact

C:\>

Поскольку это в Windows, я не хочу использовать модули os.system и subprocess, так как curl.exe не существует по умолчанию.

Здесьмои попытки ... Но я все еще не получил такой же вывод, как у curl -v

>>> import requests
>>> requests.get("http://example.com").content
>>> requests.get("http://example.com").text

>>> import pycurl                        
>>> c = pycurl.Curl()                    
>>> c.setopt(c.URL, 'http://example.com')
>>> c.perform()

Ответы [ 2 ]

0 голосов
/ 21 января 2019

Без каких-либо сторонних пакетов (например, requests) в Python 3.7.2:

>>> import urllib.request
>>> dict(urllib.request.urlopen("http://example.com").headers)
{'Accept-Ranges': 'bytes', 'Cache-Control': 'max-age=604800', 'Content-Type': 'text/html; charset=UTF-8', 'Date': 'Mon, 21 Jan 2019 02:52:13 GMT', 'Etag': '"1541025663+gzip"', 'Expires': 'Mon, 28 Jan 2019 02:52:13 GMT', 'Last-Modified': 'Fri, 09 Aug 2013 23:54:35 GMT', 'Server': 'ECS (sjc/4E8B)', 'Vary': 'Accept-Encoding', 'X-Cache': 'HIT', 'Content-Length': '1270', 'Connection': 'close'}

документы

0 голосов
/ 21 января 2019

Если вы ищете информацию о Last-Modified, Cache-Control и т. Д., В requests вы можете проверить headers.

>>> import requests
>>> req = requests.get("http://example.com")
>>> req.headers
{'Content-Encoding': 'gzip', 
'Accept-Ranges': 'bytes', 
'Cache-Control': 'max-age=604800', 
'Content-Type': 'text/html; charset=UTF-8', 
'Date': 'Mon, 21 Jan 2019 01:13:53 GMT', 
'Etag': '"1541025663"', 
'Expires': 'Mon, 28 Jan 2019 01:13:53 GMT', 
'Last-Modified': 'Fri, 09 Aug 2013 23:54:35 GMT', 
'Server': 'ECS (dca/24A0)', 
'Vary': 'Accept-Encoding', 
'X-Cache': 'HIT', 
'Content-Length': '606'}
...