【发布时间】:2012-04-23 13:35:57
【问题描述】:
当我想使用 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"
我整个星期都在努力寻找问题! 为什么我没有看到完整的页面?
感谢帮助
【问题讨论】:
-
我强烈建议使用出色的 python-requests 库而不是 urllib/urllib2。
-
没有完整页面是什么意思?你得到了什么?
-
如果您将
src写入文件,然后再将其输入BeautifulSoup,您会“获取完整页面”吗?如果是这样,BeautifulSoup可能会省略部分 HTML 源代码以便能够正确解析它。 -
@simon 你说得对,尽管使用了 bs4,但如何获取整个页面?
-
你为什么首先使用 BeautifulSoup?现在,您的代码只是将源代码插入并立即将其再次序列化。这没有多大意义......