终于采用Bs4成功爬虫一个简单的案例,小白问题多

本文介绍如何使用Python的bs4模块解析HTML文档,包括创建BeautifulSoup对象、选择标签、使用属性值查找元素的方法,以及如何将列表转换为字符串。

碰到bs4模块不可用的时候:
文件——setting添加
在这里插入图片描述
基本步骤与正则表达式一样:
1.urlopen发出请求,获取响应对象
2.获得response的响应的对象,response.read()得到源码信息,是字节,decode转换成字符串
3.解析源码,创建BS对象
使用bs4的时候,需要创建bs4对象(如果提示模块不可以,用上面的解决方法)
from bs4 import BeautifulSoup as BS
#第一个参数:要处理的字符串信息(源码)
#第二个参数:要处理的信息类型,指定是html.parser
#bs=BS(转换的源码信息"html.parser")
select(标签名):例如 bs.select(“title”)
select(.class的属性值):例如 bs.select(".sister")
find(“标签名”,{“属性名”:“属性值”}):
例如 bs.find(“a”,{“href”:“http://example.com/elsie”}))
4.存储

另外用到一个.join() 功能:能够将迭代对象中的每个元素取出,形成字符串 将列表转换成字符串。

在这里插入图片描述

使用 Pythonbs4 库进行爬虫,一般流程是先获取页面源码,再实例化一个 BeautifulSoup 对象并将页面源码加载到该对象中,最后通过调用相关属性或方法进行标签定位和数据提取[^1]。以下是一个简单案例: ```python import requests from bs4 import BeautifulSoup # 要爬取的网页 URL url = 'https://example.com' # 请替换为实际要爬取的网页 URL # 发送请求获取页面源码 response = requests.get(url) html_content = response.text # 实例化 BeautifulSoup 对象 soup = BeautifulSoup(html_content, 'html.parser') # 假设要提取所有的链接 links = soup.find_all('a') # 遍历并打印链接 for link in links: href = link.get('href') print(href) ``` 在这个案例中,首先使用`requests`库发送请求获取网页的 HTML 内容,然后使用`BeautifulSoup`将 HTML 内容加载到对象中,接着使用`find_all`方法查找所有的`<a>`标签,最后提取每个`<a>`标签的`href`属性并打印出来。 ### 案例拓展 如果有具体的 HTML 数据,如以下示例: ```python html=''' <html><head><title>The Dormouse's story</title></head> <body> <p class="title" name="dromouse"><b>The Dormouse's story</b></p> <p class="story">Once upon a time there were three little sisters; and their names were <a href="http://example.com/elsie" class="sister" id="link1"><!-- Elsie --></a>, <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>; and they lived at the bottom of a well.</p> <p class="story">...</p> ''' from bs4 import BeautifulSoup soup = BeautifulSoup(html, 'html.parser') # 提取标题 title = soup.title.string print("标题:", title) # 提取第一个 p 标签的文本 first_p_text = soup.find('p', class_='title').b.string print("第一个 p 标签文本:", first_p_text) # 提取所有 a 标签的链接 links = soup.find_all('a') for link in links: href = link.get('href') print("链接:", href) ``` 在这个拓展案例中,对给定的 HTML 数据进行解析,提取了标题、第一个`<p>`标签的文本以及所有`<a>`标签的链接。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值