#041爬虫beautifulsoup 使用信安培训2019年5月25日

爬虫beautifulsoup 使用信安培训2019年5月25日

beautifulsoup

beautifulsoup安装

 

CMD命令行pip安装beautifulsoup4库
CMD命令行pip安装beautifulsoup4库

 

学习样例题目

题目地址

题目链接

 

题目截图
题目截图

 

解题步骤

beautifulsoup 快速讲解

查看源代码

 

算式位置在p标签中 name=‘myexpr’的div中
算式位置在p标签中 name=‘myexpr’的div中

 

代码

import requests
from bs4 import BeautifulSoup
r = requests.get('http://ctf5.shiyanbar.com/jia/index.php')
r.encoding = r.apparent_encoding
soup = BeautifulSoup(r.text,'html.parser')
a = soup.find_all('div',{"name":"my_expr"})

 

匹配相应数据
匹配相应数据

 

代码2

只有一个p标签
所以可以直接这么使用直接匹配p

b=soup.p.div.get_text()

例题二爬取中国大学排名

题目地址

解析出排名和大学名称即可

 

大学排名网站
大学排名网站

 

from bs4 import BeautifulSoup
import requests

r = requests.get('http://www.zuihaodaxue.cn/zuihaodaxuepaiming2019.html')
r.encoding = r.apparent_encoding
attr = {"class":"table table-small-font table-bordered table-striped"}

soup = BeautifulSoup(r.text,'html.parser')
a = soup.find('table',attr)
a = a.find_all('tr',{"class":"alt"})
result = '排名,大学
'
for i in a:
    result += i('td')[0].text +','+i.div.text+'
'
with open('rank.csv','w') as f:
    f.write(result)
原文地址:https://www.cnblogs.com/hx97/p/10923965.html