我想要用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的内容不能每次都在控制台输出,需要多运行几次.有时运行结果如下图:
再多运行几次,才会有输出结果
之前仔细翻阅过bs4的官方文档,发现了几个小问题。
你的用法还是bs3的用法,新调用语句是
soup = BeautifulSoup(html, 'html5lib')
;最重要的是,你用了
urlopen()
,但是没有用read()
读出源码。。。有时候输不出东西或者输错东西时候,绝大多数是bs4的编码问题,它除了几个特定的IO之外几乎都是unicode编码