沭阳住房城乡建设局网站,常见的网站推广方式,莱芜二手房产网,浦北网站建设任务#xff1a;爬取B站上最爱欢迎的编程课程
网址#xff1a;编程-哔哩哔哩_bilibili
打开网页的代码模块#xff0c;如下图#xff1a; 标题均位于class_bili-video-card__info--tit的h3标签中#xff0c;下面通过代码来实现#xff0c;需要说明的是URL中…任务爬取B站上最爱欢迎的编程课程
网址编程-哔哩哔哩_bilibili
打开网页的代码模块如下图 标题均位于class_bili-video-card__info--tit的h3标签中下面通过代码来实现需要说明的是URL中的中文写到程序中已自动转义
import requests
from bs4 import BeautifulSoupurl https://search.bilibili.com/all?keyword%E7%BC%96%E7%A8%8Bfrom_sourcebanner_searchordershowduration0tids_10
headers {User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36
}
# 设置请求头模拟浏览器访问
headers {User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36
}# 发送GET请求
response requests.get(url, headersheaders)# 检查请求是否成功
if response.status_code 200:# 解析HTML内容soup BeautifulSoup(response.text, html.parser)# 查找所有h3标签h3_tags soup.find_all(h3, class_bili-video-card__info--tit)# 遍历所有h3标签提取title属性值for index, h3_tag in enumerate(h3_tags, start1):title h3_tag.get(title)if title:print(fTitle {index}: {title})else:print(fTitle {index}: 无title属性)
else:print(请求失败状态码:, response.status_code)
输出 需要注意的是网页的代码并非一成不变爬取时一定要使用F12分析其代码结构。