使用Pycurl获取HTML

Sin*_*het 9 python pycurl

我一直在尝试使用pycurl检索HTML页面,因此我可以使用str.split和一些for循环解析相关信息.我知道Pycurl检索HTML,因为它将它打印到终端,但是,如果我尝试做类似的事情

html = str(c.perform())  
Run Code Online (Sandbox Code Playgroud)

该变量只包含一个字符串,表示"无".

我如何使用pycurl来获取html,或者将它发送到控制台的任何内容重定向,以便它可以像上面描述的那样用作字符串?

非常感谢任何有任何建议的人!

Cor*_*erg 21

这将发送请求并存储/打印响应正文:

from StringIO import StringIO    
import pycurl

url = 'http://www.google.com/'

storage = StringIO()
c = pycurl.Curl()
c.setopt(c.URL, url)
c.setopt(c.WRITEFUNCTION, storage.write)
c.perform()
c.close()
content = storage.getvalue()
print content
Run Code Online (Sandbox Code Playgroud)

如果要存储响应标头,请使用:

c.setopt(c.HEADERFUNCTION, storage.write)
Run Code Online (Sandbox Code Playgroud)

  • 我认为这是正确的.注意我来自StrongIO import StringIO' (3认同)
  • 对于Python 3,使用`io.BytesIO`,但是`.getvalue()`将返回`bytes`,所以你应该用`.decode("utf-8")把它们变成字符串. (2认同)

小智 6

perform()方法执行html fetch并将结果写入您指定的函数.您需要提供一个缓冲区来将html放入和写入函数.通常,这可以使用StringIO对象来完成,如下所示:

import pycurl
import StringIO

c = pycurl.Curl()
c.setopt(pycurl.URL, "http://www.google.com/")

b = StringIO.StringIO()
c.setopt(pycurl.WRITEFUNCTION, b.write)
c.setopt(pycurl.FOLLOWLOCATION, 1)
c.setopt(pycurl.MAXREDIRS, 5)
c.perform()
html = b.getvalue()
Run Code Online (Sandbox Code Playgroud)

您还可以使用文件或临时文件或任何其他可以存储数据的内容.