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

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.csdn.net/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
...
发布了20 篇原创文章 · 获赞 24 · 访问量 2588

猜你喜欢

转载自blog.csdn.net/u011285708/article/details/104239048