Python第一个爬虫,简单爬起网页中超链接

本文介绍如何使用Python的BeautifulSoup库进行网页爬取,通过实例演示了从优快云博客页面抓取所有链接的方法。首先安装beautifulsoup4库,然后解析目标网页,最后提取并打印所有带有'http'前缀的'a'和'link'标签的href属性。

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

1、安装beautifulsoup4库

python -m pip install beautifulsoup4 或者使用源码安装

C:\Users\Administrator\Desktop\Test_Python>python -c “import bs4”

2、查看要爬取网页结构

在这里插入图片描述

可以发现里面有href属性的标签名有link或者a,那么在抓取地址的时候这两种情况都要考虑到…

3、编写爬起脚本

from urllib.request import urlopen
from bs4 import BeautifulSoup

#获取一个html对象
html = urlopen("https://blog.youkuaiyun.com/hadues/article/details/88981686")
#获取一个BeautifulSoup对象
bsObj = BeautifulSoup(html,features="html.parser")

#分两步爬取,分别爬取标签为a和link,并保存到不同步的结果集中

linksL = bsObj.findAll("link")
linksA = bsObj.findAll("a")

#创建一个列表用于存储href属性值
hrefs = []

#将字典中href属性的都追加到hrefs列表中
for link in linksA:
    if 'href' in link.attrs:
        if 'http' in link.attrs['href']:
            hrefs.append(link.attrs['href'])

for link in linksL:
    if 'href' in link.attrs:
        if 'http' in link.attrs['href']:
            hrefs.append(link.attrs['href'])

#打印出结果
for href in hrefs:
    print(href)

**爬取结果如下:**
...
https://blog.csdn.net/hadues/category_5777713.html
https://blog.csdn.net/hadues/category_9480975.html
https://blog.csdn.net/hadues/category_9480986.html
https://blog.csdn.net/hadues/category_9476952.html
...
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值