BeautifulSoup入门案例

 import beautifulsoup4 as bs
 import requests
 
 url = "http://www.baidu.com"
 html = requests.get(url)		# 获取网页响应对象
 html.encoding = 'utf-8'		# 修改网页响应对象(requests.models.Response)的编码格式
 content = html.text		# 获取网页的内容
 soup = bs(content, 'html.parser')		# 根据网页内容创建一个beautifulsoup对象, 'html.parser'为网页解析器
 
 print(soup.prettify())		# 格式化输出网页内容
 
 a_tag_set = soup.find_all('a')		# 获取网页中的所有的a标签,返回值为一个集合
 a_tag = soup.find('a') 		# 获取网页中的第一个a标签
 a_tag = soup.a		# 获取网页中的第一个a标签
 a_dict = a_tag.attrs		# 获取a标签的属性字典
 print(a_dict['href']) 		# 打印a标签中的'href'属性的值
 
 a_parent_tag_iterator = soup.a.parent		# .parent返回可迭代对象,不是列表,需要用for循环遍历其中的内容
 a_children_tag_iterator = soup.a.children 	# .children返回可迭代对象,不是列表,需要用for循环遍历其中的内容
  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值