首页 技术 正文
技术 2022年11月15日
0 收藏 558 点赞 4,267 浏览 1325 个字
import requests
from bs4 import BeautifulSoup
response = requests.get("https://www.autohome.com.cn/news/") # 01 发送请求
response.encoding = response.apparent_encoding # 格式转换防止页面中文乱码 自动获得返回数据原来的编码
# print(response.text) # 打印整个html文本soup = BeautifulSoup(response.text,features="html.parser") # 02 soup :整体的框架 把html文本转换成soup对象,features="表示引擎"
target = soup.find(id="auto-channel-lazyload-article") # 03 soup==>>div :在soup框架种找里面的文本内容先找做大的哪个div 标签 从id =" " 的标签开始
# print(target) # 只打印div标签内容li_list=target.find_all("li") # find表示只找第一个li的标签,find_all表示找所有的
# print(li_list) #打印所有的div里面的li标签,打印的是列表类型,不是 beautifulsuop 的对象for i in li_list: a = i.find("a") # 04 找soup==>>div==>>li_list :不是 beautifulsuop 的对象,是一个列表。但li_list[0]是,可以用for循环来查找
if a: # 因为有些li标签没有a 所有用个if判断语句有a的话在执行下面的
print('http:'+a.attrs.get('href')) # 打印所有li中的a标签 (a.attrs )表示找到a标签的属性值,打印所有a标签的链接 h3_txt= a.find("h3") .text # 05 找soup==>>div==>>li_list==>>h3 :查找 li 标签里面的 h3 标签 .text 获取对象的文本,返回的是字符串格式
print(h3_txt) # 打印li 标签里面的 h3 标签的内容 # type查看属性type(h3_txt) img_url = a.find('img') .attrs.get('src') # 06 找soup==>>div==>>li_list==>>img :查找 li 里面的 img 标签 并获取标签属性值,既标签的链接
print('http:'+img_url) # 打印li 标签里面的 图片链接 的内容 '''
07 保存图片到本地
'''
import uuid
image_reponse = requests.get(url='http:'+img_url) file_name = str(uuid.uuid4()) + '.jpg' # 用uuid随机生成名字 with open(file_name, 'wb') as f:
f.write(image_reponse.content) # reponse.content返回字节 reponse.text 返回的是字符串 reponse.encoding reponse.reparent_encoding自动获得返回数据原来的编码
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,088
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,565
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,413
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,186
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,822
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,905