网络爬虫:BeautifulSoup

本文介绍如何使用Python的urllib和BeautifulSoup库来抓取网页标题,并演示了异常处理的方法。此外,还详细解释了如何利用findAll方法从HTML中提取特定元素,包括属性过滤和正则表达式匹配。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

以获取网页的title为例

基础模板

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

import urllib.request
import urllib.error
from bs4 import BeautifulSoup

def get_title(url):
    req=urllib.request.Request(url)
    response=urllib.request.urlopen(req)
    html = response.read().decode("utf-8")
    soup=BeautifulSoup(html,"html.parser")
    print (soup.title)


if __name__=="__main__":
    url="http://www.pythonscraping.com/exercises/exercise1.html"
    get_title(url)

增加判断异常

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

import urllib.request
import urllib.error
from bs4 import BeautifulSoup

def get_title(url):
    try:
        req=urllib.request.Request(url)
        response=urllib.request.urlopen(req)
    except (urllib.error.HTTPError,urllib.error.URLError as e:
        print(e)
        return None
    try:
        html = response.read().decode("utf-8")
        soup = BeautifulSoup(html, "html.parser")
        title=soup.title
    except AttributeError as e:
        return None
    return title

if __name__=="__main__":
    url="http://www.pythonscraping.com/exercises/exercise1.html"
    title=get_title(url)
    if title == None:
        print("Title could not be found")
    else:
        print(title)

find()与findAll()

通过BeautifulSoup对象,可以用findAll函数抽取只包含在<-span class=”green”><-/span>标签(注:没有-符号)中的文字,这样会得到一个Python列表。

nameList=soup.findAll("span",{"class":"green"})
    for name in nameList:
        print (name.get_text())

注:什么时候使用.get_text()与什么时候应该保留标签?
.get_text()会把正在处理的HTML文档中所有的标签都清除,然后返回一个只包含文字的字符串。假如你正在处理一个包含许多超链接、段落和标签的大段源代码,那么.get_text()会把这些超链接、段落和标签都清除掉,只剩下一串不代表标签的文字。

用BeautifulSoup对象查找你想要的信息,比直接在HTML文本中查找信息要简单的多。通常在你准备打印、存储和操作数据时,应该最后才使用.get_text()。一般情况下,你应该尽可能的保留HTML文档的标签结构。
这里写图片描述
这里写图片描述
这里写图片描述

from bs4 import BeautifulSoup
import re
#根据HTML网页字符串创建BeautifulSoup对象
html_doc='<a href="/view/123.htm" class="article_link">Python</a>'
soup=BeautifulSoup(html_doc,"html.parser",from_encoding="utf-8")
#查找所有标签为a的节点
print (soup.findAll("a"))

#查找所有标签为a,链接符合/view/123.htm形式的节点
print (soup.findAll("a",href="/view/123.htm"))
print (soup.findAll("a",href=re.compile(r'/view/\d+\.htm')))

#查找所有标签为div,class为abc,文字为Python的节点
print (soup.findAll("a",class_="article_link",text="Python"))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值