欢迎加入学习交流QQ群:657341423
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 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