通过request获取网页资讯 通过BeautifulSoup剖析网页元素
2024-10-19 03:30:03
import requests
newsUrl ='http://news.sina.com.cn/china/'
res = requests.get(newsUrl)
res.encoding ='utf-8’
pint
print(res.text)
//然后通过DOM Tree来剖析网页元素
from bs4 import BeautifulSoup
html_sample ='\
<html>\
<body>\
<h1 id="title">this is h1</h1>\
<a class="link" href="fdfdfdfd">this is a link</a>\
<a class="link" href="fdfdfdfd">this is another link</a>\
</body>\
</html>'
'''
html.parser 解析器 ,不写的话会发出警告
'''
soup = BeautifulSoup(html_sample,'html.parser’)
print(soup.text)
#找出所有含特定标签的HTML元素
#1: 使用select 找出含有h1标签的元素
header = soup.select('h1’)
print(header)print(header[0].text )
#第0个标签中的文字
#2: 使用select找出含有a标签的元素
alink = soup.select('a’)
print(alink)
for link in alink:
#print(link)
print(link.text)
#取得含有特定CSS属性的元素
#1使用select找出所有id为title的元素(id前需加#)
aTitle = soup.select('#title')
print(aTitle)
#2使用select找出所有class为link的元素(class前需要加.)
for mylink in soup.select('.link'):
print(mylink)
#取得所有a标签内的链接
#使用select找出所有a tag的href连结
ahref = soup.select('a')
for ah in ahref:
print(ah['href'])
最新文章
- C 标准库系列之概述
- TTS通过JavaScript调用
- (一)u-boot-nand.bin的下载
- python数据结构-列表-基本操作
- JMeter 测试Web登录
- hdu 1242 Rescue_bfs+优先队列
- firefox必备扩展
- php实现多表(四表)连接
- .NET日志工具介绍
- find用法积累
- SQL生成一年每一天的时间列表的几种方法
- Docker 入门之创建service(一)
- Hyperledger Fabric-CA学习
- Document.write和 getElementById(ID)
- Swift中 @objc 使用介绍
- Python元组与列表的区别
- linux工具介绍
- toFixed四舍五入精度校正
- Android Studio 入门级教程(一)
- python爬虫之Scrapy框架(CrawlSpider)
热门文章
- 使用swoole编写简单的echo服务器
- 转 移动端-webkit-user-select:none导致input/textarea输入框无法输入
- .netcore webapi iis 虚拟目录下载apk文件
- u-boot之ARM920T的start.S分析
- glide install失败 Update failed for golang.org/x/net: Cannot detect VCS
- 安卓个性化 Button
- Startup.国外新锐公司及其技术Blog
- Luogu1501 Tree II - LCT
- tableView的cell之间间隔显示空白区域
- Servlet开发的三种方法