requests的用法
1.发送请求获取响应
requests.get(目标地址)
import requests
def get_html_data(url:str):
headers={
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36'
}
response=requests.get(url,headers=headers)
2.获取数据(请求结果)
注意:中文乱码在打印结果中找meta标签中的charset属性,把encoding值设为属性值
响应.text —用网页爬取结果
response.encoding = 'gbk'
print(response.text)
css选择器
1.标签选择器,元素选择器
将标签名作为选择器,选中后所有指定标签,例如:p{}–选中所有p标签
2.id选择器
在标签的id属性前加#号作为一个选择器,选中id值是指定的标签。
3.class选择器,类选择器
在class选择器前面加.作为选择器,选择class属性值是指定值的标签
注意:同一个class属性值可以有多个,同一个标签可以有多个class
.x.y —选中class属性值同时包含x,y的标签
4.群组选择器
将多个独立的选择器用逗号隔开作为一个选择器,选中每个独立选择器选中的内容
5.后代选择器
将多个独立的选择器用空格隔开作为一个选择器
6.子代选择器
将多个独立的选择器用>隔开,作为一个选择器
div>p{},选中在div中的p标签(p必须是div子代就行)
bs4数据解析
1.通过网页内容创建BuautifulSoup对象(网页内容就是需要解析的网页数据)
BeautifulSoup(html代码,'lxml)
from bs4 import BeautifulSoup
content = open('网页.html', encoding='utf-8').read()
soup = BeautifulSoup(content, 'lxml')
2.获取标签
标签对象.select(css选择器) —返回选择器中选中的所有标签
标签对象.select_one(css选择器) —返回选择器中选中的第一个标签
3.获取双标签标签内容
标签对象.text —获取指定标签的内容
4.获取标签属性
标签对象.attrs[属性名]
练习:把网页中的商品的名字,价格,图片路径爬取出来,放入字典中存储
from bs4 import BeautifulSoup
content = open('网页.html', encoding='utf-8').read()
soup = BeautifulSoup(content, 'lxml')
all_data = []
for product in soup.select('li'):
p_dict = {}
p_dict['name'] = product.select('p')[0].text
p_dict['price'] = float(product.select('.price')[0].text[1:])
p_dict['img'] = product.select('img')[0].attrs['src']
all_data.append(p_dict)
print(all_data)
"""
[{'name': '泡面', 'price': 3.5, 'img': 'https://img1.baidu.com/it/u=3160659086,3725745087&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500'}, {'name': '火腿肠', 'price': 2.5, 'img': 'https://img0.baidu.com/it/u=1309756832,682125188&fm=26&fmt=auto'}, {'name': '可乐', 'price': 3.0, 'img': 'https://img0.baidu.com/it/u=707176316,890856051&fm=26&fmt=auto'}]
"""