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
...