@websec007
2020-08-13T09:00:04.000000Z
字数 1754
阅读 1043
爬虫学习
requests库是一个模仿浏览器客户端向服务器发送网页请求的第三方python库;
# requests 镜像安装pip install requests -i https://mirrors.aliyun.com/pypi/simples
# 导入库import requests# 发送情况,获取响应url = https://xxx.comresponse = requests.get(url)# 获取响应数据response.encoding = 'utf-8'print(response.content)print(response.text)print(response.content.decode('utf-8'))
# 将二进制流转换为字符串,并打印输出print(response.content.decode('utf-8'))# 指定响应体编码方式为utf-8,然后打印输出响应体字符类数据response.coding = 'utf-8'print(response.text)
# 导入第三方模块import requests# 发送get请求,获取响应体url = 'https://www.baidu.com'response = request.get(url)# 获取响应体文本内容text = response.content.encode('utf-8')print(text)# 或使用以下方法# response.encoding = 'utf-8'# text = response.text
BeautifulSoup 是一个可以从html 或 xml中提取数据的第三方库。
# 安装 bs4pip install bs4# 安装 lxmlpip instal lxml
# 导入模块from bs4 import BeautifulSoup4# 指定解析器进行html文档的解析soup = BeautifulSoup('<html>data</html>', 'lxml')print(soup.prettify())
tag_a = soup.find('a')
attr = soup.find(id='link1')或attr = soup.find(attrs={'id':'link1'})
text = soup.find(text='Elise')
tags_a = soup.findall('a')
什么是Tag对象?
我们可以直接打印下以
Tag标签的类型,就可以看到其就是Tag类型。
a = soup.find('a')print(type(a))# 打印输出结果如下<class 'bs4.element.Tag'>
Tag对象的属性
tag = soup.find('title')print(tag.name)print(tag.attrs)print(tag.text)
