时间: 2020-11-26|48次围观|0 条评论

安装BeautifulSoup

1.Linux 系统上的安装:

  sudo apt-get install python-bs4

2.Mac系统

  pip install beatifulsoup4

3.Windows系统

  pip install beatifulsoup4

 

html = urlopen("http://www.baidu.com")

这行代码可能出现两种异常

1.网页在服务器上不存在

2.服务器不存在

第一种会抛出HTTPError异常

第二种会抛出HTMLError异常

如果调用的标签不存在,就会返回AttributeError

 

返回网页标题的封装函数

from urllib.request import urlopen
from urllib.error import HTTPError,URLError
from bs4 import BeautifulSoup
def getTitle(url):
    try:
        html = urlopen(url)
    except (HTTPError,URLError) as e:
        return None
    try:
        bs0bj = BeautifulSoup(html.read())
        title = bs0bj.body.h1
    except AttributeError as e:
        return None
    return title


title = getTitle("https://www.douban.com")
if title == None:
    print("Title could not be found")
else:
    print(title)

 

转载于:https://www.cnblogs.com/Little-Raccoon/p/10998026.html

原文链接:https://blog.csdn.net/weixin_30342827/article/details/98670115

本站声明:网站内容来源于网络,如有侵权,请联系我们,我们将及时处理。

本博客所有文章如无特别注明均为原创。
复制或转载请以超链接形式注明转自起风了,原文地址《BeautifulSoup
   

还没有人抢沙发呢~