Python Beautiful Soup+requests实现爬虫

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Xy-Huang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值