首页 > 用BeautifulSoup提取网页内容时有时无显示

用BeautifulSoup提取网页内容时有时无显示

我想要用python提取新浪财经文章的html,在控制台输出.用了BeautifulSoup,代码如下:

# -*- coding: utf-8 -*-

from bs4 import BeautifulSoup
import re
import urllib
import urllib2

url='http://finance.sina.com.cn/stock/t/2015-12-16/doc-ifxmszek7156687.shtml'
user_agent='Mozilla/4.0(compatible;MSIE 5.5;Windows NT)'
headers={'User-Agent':user_agent}
try:
    request=urllib2.Request(url,headers=headers)
    response=urllib2.urlopen(request)
    content=BeautifulSoup(response)
    print content
except  urllib2.URLError,e:
       if hasattr(e,"code"):
          print e.code
       if hasattr(e,"reason"):
          print e.reason

但是问题是,运行时,content的内容不能每次都在控制台输出,需要多运行几次.有时运行结果如下图:

再多运行几次,才会有输出结果


写程序,功能分步骤来嘛。
就像走路,想'走'到街对面至少得一步步的'走'。
那么对于你的代码

request=urllib2.Request(url,headers=headers)
response=urllib2.urlopen(request)
content=BeautifulSoup(response)

3行代码,分割即为两部分。
1、页面请求
2、结果分析

那么就找问题点一个个分析排除好了,盯着最终的结果是得不到答案的。


之前仔细翻阅过bs4的官方文档,发现了几个小问题。

  1. 你的用法还是bs3的用法,新调用语句是soup = BeautifulSoup(html, 'html5lib')

  2. 最重要的是,你用了urlopen(),但是没有用read()读出源码。。。

  3. 有时候输不出东西或者输错东西时候,绝大多数是bs4的编码问题,它除了几个特定的IO之外几乎都是unicode编码

【热门文章】
【热门文章】