【问题标题】:using python urllib2 to send POST request and get response使用 python urllib2 发送 POST 请求并获得响应
【发布时间】:2012-09-13 04:58:12
【问题描述】:

我正在尝试通过发送 POST 请求来获取 HTML 页面:

import httplib 
import urllib 
import urllib2 
from BeautifulSoup import BeautifulSoup


headers = {
    'Host': 'digitalvita.pitt.edu',
    'Connection': 'keep-alive',
    'Content-Length': '325', 
    'Origin': 'https://digitalvita.pitt.edu',
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_4) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1',
    'Content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
    'Accept': 'text/javascript, text/html, application/xml, text/xml, */*',
    'Referer': 'https://digitalvita.pitt.edu/index.php',
    'Accept-Encoding': 'gzip,deflate,sdch',
    'Accept-Language': 'en-US,en;q=0.8',
    'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
    'Cookie': 'PHPSESSID=lvetilatpgs9okgrntk1nvn595'
}

data = {
    'action': 'search',
    'xdata': '<search id="1"><context type="all" /><results><ordering>familyName</ordering><pagesize>100000</pagesize><page>1</page></results><terms><name>d</name><school>All</school></terms></search>',
    'request': 'search'
}

data = urllib.urlencode(data) 
print data 
req = urllib2.Request('https://digitalvita.pitt.edu/dispatcher.php', data, headers) 
response = urllib2.urlopen(req)
the_page = response.read()

soup=BeautifulSoup(the_page)
print soup

谁能告诉我如何让它工作?

【问题讨论】:

  • 您查看过requests 库吗?它使 http 请求更容易。您还缺少一些回车符,例如在你的 import 语句之间,在你的 print 语句之前。这些是否也存在于您的原始代码中?
  • 看看错误信息会很有帮助
  • 使用pycurl更简单更干净:stackoverflow.com/questions/22799648/…

标签: python post request beautifulsoup urllib2


【解决方案1】:

不要指定Content-Length 标头,urllib2 会为您计算。实际上,您的标头指定了错误的长度:

>>> data = urllib.urlencode(data) 
>>> len(data)
319

没有该标题,其余发布的代码对我来说都可以正常工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-20
    • 1970-01-01
    • 2016-11-28
    • 1970-01-01
    • 1970-01-01
    • 2020-07-29
    相关资源
    最近更新 更多