python,没有得到完整的响应
当我想使用urllib2获取页面时,我无法获取完整页面 以下是python中的代码:python,没有得到完整的响应,python,url,urllib2,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 webpag
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
我也有同样的问题,我认为这是urllib,但它是bs4 代替使用
BeautifulSoup(src)
或
试用
soup = bs4.BeautifulSoup(html, 'html5lib')
我强烈建议使用奇妙的库,而不是urllib/urllib2。不获取完整页面是什么意思?你得到了什么?如果你在把
src
输入到BeautifulSoup
之前,先把它写入一个文件,你会“得到完整的页面”吗?如果是这样,BeautifulSoup
可能会省略部分HTML源代码,以便能够正确解析它。@simon你是对的,尽管使用了bs4,如何获得整个页面?你为什么要首先使用BeautifulSoup?现在,您的代码只是将源代码插入并立即将其再次序列化。这没有多大意义…@aminonsh如果指定显式块大小,它会改变什么吗?(我修改了我的答案)@aminonsh,你100%确定在任何漂亮的汤解析之前src是不完整的?你有没有试过在同一个URL上运行wget,并将下载的文件与src的内容进行比较?您不应该与浏览器中显示的源代码进行比较,因为该站点可能会使用javascript1进行浏览器检测或修改代码。我用我的浏览来比较它。让我澄清一下:1。如果我从浏览器中查看源代码,我可以得到标签2。但是在用python的gedit(接收到的数据)打开它之后,我没有得到标签3。这意味着我没有得到完整的页面!!!因此,如果您将写入文件(获取页面(url))
并将结果文件与控制台上的wget url
进行比较,它是您获取的文件的前N个字节?N有多大?好吧,我的错。bs4制作胸针。我得到了整个响应,但当使用soup=BeautifulSoup(src)时,我得到了页面的一半!!为什么?
soup = bs4.BeautifulSoup(html, 'html5lib')