Python——网络数据采集(一)

  1. 使用原始的urllib库请求网站访问;
  2. 使用beautifulsoup库解析网站的元素;
  3. 考虑是否会有报错的情况,做优化。
from urllib.request import urlopen 
from bs4 import BeautifulSoup 
html = urlopen("http://www.baidu.com") 
bsObj = BeautifulSoup(html.read()) 
print(bsObj.div)

常见的错误提示一:

当网页在服务器上不存在(或者获取页面的时候出现错误)时,程序会返回 HTTP 错误。HTTP 错误可能是“404 Page Not Found”“500 Internal Server Error”等。

try:     
    html = urlopen("http://www.pythonscraping.com/pages/page1.html") 
except HTTPError as e:     
    print(e)     # 返回空值,中断程序,或者执行另一个方案 
else:     
    # 程序继续。注意:如果你已经在上面异常捕捉那一段代码里返回或中断(break),
    # 那么就不需要使用else语句了,这段代码也不会执行

常见的错误提示二:

当服务器不存在时,(就是说链接 http://www.pythonscraping.com/ 打不开,或者是 URL 链接 写错了),urlopen 会返回一个 None 对象。这个对象与其他编程语言中的 null 类似。我们 可以增加一个判断语句检测返回的 html 是不是 None。

if html is None:     
    print("URL is not found") 
else:     
    # 程序继续

于是,完整的网站页面请求为:

from urllib.request import urlopen 
from urllib.error import HTTPError 
from bs4 import BeautifulSoup     
    
def getTitle(url):         
    try:
        html = urlopen(url)         
    except HTTPError as e:             
        return None         
    try:             
        bsObj = BeautifulSoup(html.read())             
        title = bsObj.div#u1.text()
    except AttributeError as e:             
        return None         
    return title 
title = getTitle("http://www.baidu.com") 
if title == None:     
    print("Title could not be found") 
else:     
    print(title)

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值