BeautifulSoup应用实例

BeautifulSoup应用实例,第1张

1 目标分析

 2  实现代码

from requests import get
from bs4 import BeautifulSoup
"""  
url="http://news.xhu.edu.cn/"
response=get(url)
response.encoding = 'utf8'
html=response.text
soup=BeautifulSoup(html,"html.parser")

a2=soup.find('div',attrs={"id":"wp_news_w4"})  #根据标签ID查找结点
#print(a2)
num=1
a3=a2.select("a")
for i  in a3:
    #print(i.get_text())
    print(num,url+i["href"],i.get_text())
    num=num+1
    print()
"""
url="http://news.xhu.edu.cn/zhxw/list.htm"
response=get(url)
print(response.status_code)
response.encoding = 'utf8'
html=response.text
soup=BeautifulSoup(html,"html.parser")

#a2=soup.find('div',attrs={"id":"wp_news_w4"})  
a2=soup.select(".wp_article_list") #根据class查找结点

listDate=[]
listTitle=[]
listHref=[]

a3=a2[0]  #获取列表第一个元素
for i in a3.children:
    soup = BeautifulSoup(str(i),"html.parser")   #重新构造soup
    #获取日期
    s=soup.select(".Article_PublishDate") #根据class获取结点
    for x in s:
        listDate.append(x.getText()) #获取类容

    #获取超链接
    s=soup.select("a")   #根据标签获取结点
    for x in s:
        listHref.append(x["href"])   #获取结点属性值
        listTitle.append(x.getText()) #获取属性文本

for i in range(len(listDate)):
    print(i+1,listDate[i],listHref[i],listTitle[i])


3  结果

200
1 2022-05-09 /b8/40/c986a178240/page.htm 我校档案工作创新做法入选 “十三五”四川省档案馆工作创新案例
2 2022-05-09 /b8/3e/c986a178238/page.htm 【访企拓岗】应急管理学院赴四川众望安全环保技术咨询有限公司开展访企拓岗促就业专项行动
3 2022-05-09 /b8/3d/c986a178237/page.htm 我校辅导员工作室入选首批四川省高校思想政治教育名师工作室
4 2022-05-09 /b8/31/c986a178225/page.htm 校领导深入巡察组指导首轮巡察工作
5 2022-05-09 /b8/2a/c986a178218/page.htm 【访企拓岗】汽车与交通学院赴中自科技公司开展“访企拓岗”暨校企交流活动
6 2022-05-07 /b8/17/c986a178199/page.htm 西华大学召开安全稳定工作会
7 2022-05-07 /b7/c5/c986a178117/page.htm 【访企拓岗】建筑与土木工程学院与四川路桥集团公路三分公司共同举办“访企拓岗”活动暨院企合作交流会
***********
18 2022-04-29 /b6/db/c986a177883/page.htm 西华大学完成2022年硕士研究生招生复试录取工作

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/904739.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-15
下一篇 2022-05-15

发表评论

登录后才能评论

评论列表(0条)

保存