requests、伪装浏览器、bs4
图片下载
import requests
def download_image(url: str):
# 1.对图片地址发送请求
response = requests.get(url)
# 2.获取图片数据
data = response.content
# 3.将数据写入到文件中
with open('files/三笠.jpg', 'wb') as f:
f.write(data)
if __name__ == '__main__':
download_image(
'https://ss0.baidu.com/7Po3dSag_xI4khGko9WTAnF6hhy/baike/pic/item/f2deb48f8c5494eee7c8465e2cf5e0fe98257e8a.jpg')
图片批量下载
from re import findall
from uuid import uuid1 # 可以创建一个唯一的id值
import requests
def download_image(url: str):
# 1.对图片地址发送请求
response = requests.get(url)
# 2.获取图片数据
data = response.content
# 3.将数据写入到文件中
with open(f'files/image/{uuid1()}.jpg', 'wb') as f:
f.write(data)
# 1.获取整个页面的数据
response = requests.get('https://cd.zu.ke.com/zufang')
content = response.text
print(content)
# 2.解析数据获取所有房屋的图片地址
all_image = findall(r'data-src="(.+?)"', content)
print(all_image, len(all_image))
# 3.下载所有图片
for i in all_image:
download_image(i)
浏览器伪装
import requests
res = requests.get(
url='https://movie.douban.com/top250',
headers={
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.0.0 Safari/537.36'
}
)
print(res)
print(res.text)
bs4数据解析
# 1.bs4的作用
"""
专门用来解析网页数据的第三方库.(基于css选择器解析网页数据)
这个库下载的时候用'beautifulsoup4',使用的时候用'bs4'
注意:在使用bs4做数据解析的时候,需要依赖'lxml'这个第三方库
"""
# 导入解析相关类
from bs4 import BeautifulSoup
# 2.bs4的用法
# 1)准备需要解析的数据(获取网页数据)
html = open('files/test.html', encoding='utf8').read()
# 2)基于网页源代码创建BeautifulSoup对象
# soup对象代表网页对应的html标签(代表整个网页)
soup = BeautifulSoup(html, 'lxml')
# 3)获取标签
# soup.select(css选择器) - 获取css选择器选中的所有标签,返回值是一个列表,列表中元素是标签对象
# soup.select_one(css选择器) - 获取css选择器选中的第一个标签,返回值是标签对象
result = soup.select('p')
print(result) # [<p>x憨憨</p>, <p>阿甘正传</p>, <p>芜湖</p>, <p>段落一</p>]
result = soup.select_one('p')
print(result) # <p>x憨憨</p>
# 标签对象.select(css选择器) - 在指定标签中获取css选择器选中的所有标签,返回值是一个列表,列表中的元素是标签对象
# 标签对象.select_one(css选择器) - 在指定标签中获取css选择器选中的第一个标签,返回值是标签对象
result = soup.select('p')
print(result) # [<p>x憨憨</p>, <p>阿甘正传</p>, <p>芜湖</p>, <p>段落一</p>]
box2 = soup.select_one('#box2')
result = box2.select('p')
print(result) # [<p>芜湖</p>]
# 4)获取标签内容和标签属性
p = soup.select_one('p')
img = soup.select_one('img')
# a.获取标签内容:标签对象.text
print(p.text) # x憨憨
# b.获取标签属性:标签对象.attrs[属性名]
print(img.attrs['src'], img.attrs['alt']) # 三笠.jpg 三笠