爬虫——beautiful演练及语法
将html文档转换成beautiful对象,然后调用属性和方法进行定位解析
主要语法:
-
创建Beatiful对象:
本地:BeautifulSoup(open('本地文件'), 'lxml')
网络:Beatiful('网络请求到的页面数据','lxml') -
获取a标签属性:soup.a['href']
-
获取文本内容:
soup.a.string 相当于xpath中的 /text()
soup.a.text 相当于xpath中的 //text() -
soup.find('a', title="xxx")
-
soup.find('div',class_='song')
# 使用bs4实现将诗词名句网站中三国演义小说的每一章的内容爬去到本地磁盘进行存储 # http://www.shicimingju.com/book/sanguoyanyi.html import requests from bs4 import BeautifulSoup as BS
# 指定url url='http://www.shicimingju.com/book/sanguoyanyi.html' headers={ "User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36" }
# 发送请求 response=requests.get(url=url,headers=headers)
# 获取返回响应对象 page_text= response.text
# 解析 soup= BS(page_text,'lxml')
# 找到所有的目标a标签 a_list= soup.select('.book-mulu > ul > li > a ')
# 元素可以继续调用解析属性和方法 # print(a_list)
f = open('./sanguo.txt','w',encoding='utf-8')
for a in a_list: title = a.string # a标签:/book/sanguoyanyi/1.html # 完整的:http://www.shicimingju.com/book/sanguoyanyi/13.html content_url='http://www.shicimingju.com'+ a['href']
# 最好封装下函数
content_page = requests.get(url=content_url,headers=headers).text soup = BS(content_page,'lxml') # p_list = soup.select('.chapter_content > p') 找出p标签还得循环取值不好 content=soup.find('div',class_='chapter_content').text f.write(title+' '+content+' ')
print('已完成')
相关文章
- Python使用tkinter组件Label显示简单数学公式
- 内网渗透之DCOM横向移动
- 以目标为导向的语义交流的共同语言——一个课程学习框架
- python爬虫前奏【成信笔记】
- HTML 5 File API:文件拖放上传功能
- 教你快速创建 Python 虚拟环境
- pyenv 实现Python多版本自由切换
- 用 Python 对 Excel文件进行批量操作
- Python - 接入钉钉机器人
- Python - 抓取 iphone13 pro 线下店供货信息并发送到钉钉机器人,最后设置为定时任务
- crontab - 解决 mac 下通过 crontab 设置了 Python 脚本的定时任务却无法运行
- [源码解析] PyTorch分布式(5) ------ DistributedDataParallel 总述&如何使用
- Python科普系列——类与方法(上篇)
- SAP对STO的交货单执行PGI,报错 -Fld selectn for mvmt type 643 acct 400020 differs
- Spring Boot 实现通用 Auth 认证的 4 种方式
- 盘点4种使用Python批量合并同一文件夹内所有子文件夹下的Excel文件内所有Sheet数据
- OushuDB 学习经验分享(三):技术特点
- Java和Python思维方式的不同之处
- Python中日志记录新技能
- 奥比中光Gemini OpenCV—Python使用