python,没有得到完整的响应

标签 python url urllib2

当我想使用 urllib2 获取页面时,我没有得到完整的页面。

这是Python代码:

import urllib2
import urllib
import socket
from bs4 import BeautifulSoup
# define the frequency for http requests
socket.setdefaulttimeout(5)

    # getting the page
def get_page(url):
    """ loads a webpage into a string """
    src = ''

    req = urllib2.Request(url)

    try:
        response = urllib2.urlopen(req)
        src = response.read()
        response.close()
    except IOError:
        print 'can\'t open',url 
        return src

    return src

def write_to_file(soup):
    ''' i know that I should use try and catch'''
    # writing to file, you can check if you got the full page
    file = open('output','w')
    file.write(str(soup))
    file.close()



if __name__ == "__main__":
            # this is the page that I'm trying to get
    url = 'http://www.imdb.com/title/tt0118799/'
    src = get_page(url)

    soup = BeautifulSoup(src)

    write_to_file(soup)    # open the file and see what you get
    print "end"

我整个星期都在努力寻找问题!! 为什么我看不到完整的页面?

感谢帮助

最佳答案

您可能需要多次调用 read,只要它不返回指示 EOF 的空字符串即可:

def get_page(url):
    """ loads a webpage into a string """
    src = ''

    req = urllib2.Request(url)

    try:
        response = urllib2.urlopen(req)
        chunk = True
        while chunk:
            chunk = response.read(1024)
            src += chunk
        response.close()
    except IOError:
        print 'can\'t open',url 
        return src

    return src

关于python,没有得到完整的响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10102696/

相关文章:

javascript - 用于编辑当前 URL 的书签

http - IIS - 当 url 中有欧洲字符时,请求被 HTTP 过滤器拒绝

python - 寻找一种方法来取消引用包含在 python 命令调用中的 bash var

javascript - 为什么在 url 中使用 'at' (@) 符号而不是 'hash' (#)

python - pandas.DataFrame.groupby.nunique() 不会删除 groupby 列。这是一个错误吗?

python urllib2请求在前面添加换行符来发布数据

python - 为什么 urllib 会出现这个错误?

Python urllib 帖子的内容类型与 urlencoded 不同

python - 如何监控 Gensim LDA 模型的收敛性?

python - 如何生成所有可能的二元 nxn 矩阵,其中每行的总和为 1