Python Beautiful Soup+requests实现爬虫
来源:互联网 发布:mac怎么安装阿里旺旺 编辑:程序博客网 时间:2024/05/29 11:18
Python 爬虫库大概有 标准库 urllib 或第三方库 requests,scrapy,BeautifulSoup 用于获取数据网站较多。scrapy其实是框架形式,适用于大规模爬取,requests就是通过http的post,get方式实现爬虫。Beautiful Soup 是一个可以从HTML或XML文件中提取数据的Python库
本次介绍Beautiful Soup+requests实现爬虫,这方法结合最简单容易上手。requests主要用get获取html信息,Beautiful Soup对Html内容进行筛选,获取自己想要的内容。
Beautiful Soup安装:
pip install beautifulsoup4
安装完后还需安装
pip install lxml
pip install html5lib
requests安装
pip install requests
requests获取网站Html内容
import requestsfrom bs4 import BeautifulSoupr = requests.get(url='https://www.baidu.com/') # 最基本的GET请求print(r.status_code) # 获取返回状态r.encoding = 'utf-8' #没有的话,中文会显示乱码print(r.text)
使用BeautifulSoup解析这段代码
soup = BeautifulSoup(r.text,"html.parser")print(soup.prettify())
运行结果:
这个涉及到编码的问题了。网上找了很多资料都无法解决。最后发现,这个问题是print的问题。
在代码中加入,即可解决
import sysimport iosys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='gb18030')
如果要将soup.prettify()写入txt
f =open("ttt.txt","w",encoding='utf-8')f.write(soup.prettify())
完整代码
from bs4 import BeautifulSoupimport requestsimport sysimport iosys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='gb18030')page = requests.get('https://www.baidu.com/')page.encoding = "utf-8"soup = BeautifulSoup(page.text,"html.parser")print(soup.prettify())f =open("ttt.txt","w",encoding='utf-8')f.write(soup.prettify())
BeautifulSoup官网文档
https://www.crummy.com/software/BeautifulSoup/bs4/doc/index.zh.html
欢迎加入学习交流QQ群:657341423
0 0
- Python Beautiful Soup+requests实现爬虫
- Python爬虫利器Beautiful Soup
- python爬虫利器--beautiful Soup
- python requests模块和Beautiful Soup模块
- Python爬虫入门-Beautiful Soup的用法
- Python爬虫利器Beautiful Soup的用法
- python 网络爬虫 Beautiful Soup用法
- 六.Python爬虫Beautiful Soup的用法
- python爬虫-Beautiful Soup学习笔记
- 【Python】【爬虫】关于Beautiful Soup库
- python安装beautiful soup库,和requests库
- 爬虫:Beautiful Soup
- Beautiful Soup写爬虫
- 爬虫---Beautiful Soup库
- webbrowser、requests、Beautiful Soup学习
- 爬虫 Python爬虫利器二之Beautiful Soup的用法
- python下很帅气的爬虫包 - Beautiful Soup 示例
- Python爬虫入门八之Beautiful Soup的用法
- C++第1次实验-【项目2】分段函数求值
- 一致性Hash算法
- Linux IP_FORWARD说明
- How to resize /dev/mapper/centos-home
- MySql学习(二)
- Python Beautiful Soup+requests实现爬虫
- PAT 1107
- MySQL数据库编程开发规范
- 如何在 Mac 上查看 Wi-Fi 密码
- mybatis 动态 SQL
- ADMM算法求解一个简单的例子
- PWA 程序开发实践
- linux ----- pwd
- Codeforces 779A-Pupils Redistribution