Python Beautiful Soup+requests实现爬虫
2017-02-27 15:38
656 查看
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内容
使用BeautifulSoup解析这段代码
运行结果:
这个涉及到编码的问题了。网上找了很多资料都无法解决。最后发现,这个问题是print的问题。
在代码中加入,即可解决
如果要将soup.prettify()写入txt
完整代码
BeautifulSoup官网文档
https://www.crummy.com/software/BeautifulSoup/bs4/doc/index.zh.html
欢迎加入学习交流QQ群:657341423
本次介绍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 requests from bs4 import BeautifulSoup r = 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 sys import io sys.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 BeautifulSoup
import requests
import sys import io sys.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
相关文章推荐
- 使用requests+beautifulsoup模块实现python网络爬虫功能
- python+beautifulsoup/xpath实现新浪微博某互粉好友全部好友圈微博爬虫
- 【Python爬虫】requests+Beautifulsoup存入数据库
- Python 爬虫—— requests BeautifulSoup
- Python爬虫知识(1)——scrapy vs requests+BeautifulSoup
- Python爬虫入门之一-requests+BeautifulSoup
- python 爬虫试手 requests+BeautifulSoup
- python简单爬虫开发(urllib2、requests + BeautifulSoup)
- Python + Requests + BeautifulSoup每日BUG汇总
- Python爬虫入门八之Beautiful Soup的用法
- python+beautifulsoup/xpath实现新浪微博已删除图片恢复(复杂度很高只介绍原理)
- Python requests+gevent+BeautifulSoup lxml 干点啥-加点速
- Python爬虫利器二之Beautiful Soup的用法【转过来,乱了,从原网址看】
- python eclipse 插件安装 及BeautifulSoup requests selenium在线安装 PhantomJS 安装 环境配置
- python+beautifulsoup/xpath实现 b站弹幕批量发送器
- Python爬虫基础细节(urllib+cookielib+BeautifulSoup)
- Python爬虫利器二之Beautiful Soup的用法
- Python爬虫利器二之Beautiful Soup的用法
- Python爬虫利器二之Beautiful Soup的用法