当前位置: 首页 > news >正文

爬虫爬取网页的信息与图片的方法

爬虫爬取网页的信息与图片的方法

  • 爬取人物信息

import requestshead = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36 Edg/126.0.0.0"
}
# 这是get请求带参数的模式
def get_param():# 1、urlurl = "https://www.sogou.com/web?"# 2、发送请求 get带参数使用params参数response = requests.get(url, headers=head, params={"query": "刘亦菲"})# 3、获取想要的数据with open("./dilireba.html", "w", encoding="utf8") as fp:fp.write(response.text)print(type(response.text))pass
get_param()

在这里插入图片描述

  • 爬取动态变换的数据(如:翻译)

import requests
def post_data():# 1、urlurl = 'https://fanyi.baidu.com/sug'# 2、发送请求response = requests.post(url, headers=head, data={"kw": "dog"})# 获取想要的数据print(response.json())
post_data()

在这里插入图片描述

  • 爬取具体位置的数据的方法

import requests
from lxml import etree
if __name__ == '__main__':tree = etree.parse("./test.html")#读取文件# xpath返回的都是列表# / 标识一个层级print(tree.xpath("/html/body/div/p"))#找到想要数据的位置print(tree.xpath("/html/head/title"))# 定位百里守约  索引定位 从1开始print(tree.xpath("/html/body/div[1]/p"))#读取第一个div的pprint(tree.xpath("/html/body/div/p[1]"))#读取body下面所有div下的第一个p#print(tree.xpath("/html/body/div[2]/a[2]"))print(tree.xpath("/html/body/div[3]/ul/li[3]/a"))## # // 标识多个层级 属性定位 attr = class id# 定位李清照print(tree.xpath("//div[@class='song']/p[1]"))#查看class或id 对应的信息是不是独一无二的,如是采用div[@class='song']这种形式,如不是查看其上一级是不是独一无二的。print(tree.xpath("//div[@class='song']/a[@class='du']"))# # 取所有的li标签print(tree.xpath("//div[@class='tang']/ul/li"))# # 取li标签内的所有a标签for li in tree.xpath("//div[@class='tang']/ul/li"):try:#数据正确print("".join(li.xpath("./a/text()")))#将列表形式变成字符串形式except Exception as e:#数据失败,执行下一个,不会影响其他数据执行pass## # 取标签下的直系文本内容print(tree.xpath("/html/body/div[1]/p/text()"))# 取标签下的所有文本print(tree.xpath("/html/body/div[2]//text()"))# 取标签内的属性值 @attr_nameprint(tree.xpath("//div[@class='song']/img/@src"))

在这里插入图片描述
在这里插入图片描述

test.html文件
<html lang="en"><head><meta charset="UTF-8" /><title>测试bs4</title></head><body><div><p>百里守约</p></div><div class="song">你好<p>李清照</p><p>王安石</p><p>苏轼</p><p>柳宗元</p><a href="http://www.song.com/" title="赵匡胤" target="_self"><span>this is span</span>宋朝是最强大的王朝,不是军队的强大,而是经济很强大,国民都很有钱</a><a href="" class="du">总为浮云能蔽日,长安不见使人愁</a><img src="http://www.baidu.com/meinv.jpg" alt="" /></div><div class="tang"><ul>清明时节雨纷纷,路上行人欲断魂<li><a href="http://www.baidu.com" title="qing">清明时节雨纷纷,路上行人欲断魂,借问酒家何处有,牧童遥指杏花村</a></li><li><a href="http://www.163.com" title="qin">秦时明月汉时关,万里长征人未还,但使龙城飞将在,不教胡马度阴山</a></li><li><a href="http://www.126.com" alt="qi">岐王宅里寻常见,崔九堂前几度闻,正是江南好风景,落花时节又逢君</a></li><li><a href="http://www.sina.com" class="du">杜甫</a></li><li><a href="http://www.dudu.com" class="du">杜牧</a></li><li><b>杜小月</b></li><li><i>度蜜月</i></li><li><a href="http://www.haha.com" id="feng">凤凰台上凤凰游,凤去台空江自流,吴宫花草埋幽径,晋代衣冠成古丘</a></li></ul></div></body>
</html>
  • 爬取网页(豆瓣TOP250的数据)

# pip install fake_useragent
import timeimport requests
import fake_useragent
from lxml import etree
import reif __name__ == '__main__':# UA伪装head = {# "User-Agent" : "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36 Edg/126.0.0.0""User-Agent": fake_useragent.UserAgent().random}# 打开一个文件写入数据fp = open("./doubanFilm.txt", "w", encoding="utf8")# 1、url# url = "https://movie.douban.com/top250"# url2 = "https://movie.douban.com/top250?start=25&filter="# url3 = "https://movie.douban.com/top250?start=50&filter="for i in range(0, 250, 25):#所有网页地址url = f"https://movie.douban.com/top250?start={i}&filter="time.sleep(5)# 2、发送请求response = requests.get(url, headers=head)# 3、获取想要的数据res_text = response.text# 4、数据解析tree = etree.HTML(res_text)# 定位所有的li标签li_list = tree.xpath("//ol[@class='grid_view']/li")  # 所有的li标签,包含信息for li in li_list:film_name = "".join(li.xpath(".//span[@class='title'][1]/text()"))  # 改成字符串形式director_actor_y_country_type = "".join(li.xpath(".//div[@class='bd']/p[1]/text()"))score = "".join(li.xpath(".//span[@class='rating_num']/text()"))quote = "".join(li.xpath(".//span[@class='inq']/text()"))# director_actor_y_country_type需要修改new_str = director_actor_y_country_type.strip()  # 去除空格y = re.match(r"([\s\S]+?)(\d+)(.*?)", new_str).group(2)  # 正则表达式方式country = new_str.rsplit("/")[-2].strip()types = new_str.rsplit("/")[-1].strip()director = re.match(r"导演: ([a-zA-Z\u4e00-\u9fa5·]+)(.*?)", new_str).group(1)try:actor = re.match(r"(.*?)主演: ([a-zA-Z\u4e00-\u9fa5·]+)(.*?)", new_str).group(2)except Exception as e:actor = "no"fp.write(film_name + "#" + y + "#" + country + "#" + types + "#" + director + "#" +actor + "#" + score + "#" + quote + "\n")  # 连接信息,连接符最好采用不常见的符号防止误读取print(film_name, y, country, types, director, actor, score, quote)fp.close()

在这里插入图片描述

  • 爬取图片

import os.path
import fake_useragent
import requests
from lxml import etree
# UA伪装
head = {"User-Agent": fake_useragent.UserAgent().random#自动伪装
}
pic_name = 0
def request_pic(url):# 2、发送请求response = requests.get(url, headers=head)# 3、获取想要的数据res_text = response.text# 4、数据解析tree = etree.HTML(res_text)li_list = tree.xpath("//div[@class='slist']/ul/li")#获取所有的照片信息for li in li_list:# 1、获取照片的urlimg_url = "https://pic.netbian.com" + "".join(li.xpath("./a/img/@src"))#img/@src,代表img的src属性# 2、发送请求img_response = requests.get(img_url, headers=head)# 3、获取想要的数据img_content = img_response.contentglobal pic_namewith open(f"./picLib/{pic_name}.jpg", "wb") as fp:#命名照片名称,并写下fp.write(img_content)pic_name += 1
if __name__ == '__main__':if not os.path.exists("./picLib"):#若没有一个此文件夹,建立一个文件夹存放照片os.mkdir("./picLib")# 1、urlurl = "https://pic.netbian.com/4kdongman/"request_pic(url)for i in range(2,10):#之后照片的urlnext_url = f"https://pic.netbian.com/4kdongman/index_{i}.html"request_pic(next_url)pass

在这里插入图片描述

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • SpringCloud03_loadbalancer的概述、负载均衡解析、切换、原理
  • Synchronized升级到重量级锁会发生什么?
  • 任务2:python+InternStudio 关卡
  • 第五节shell脚本中的运行流程控制(3)
  • 智能水果保鲜度检测:基于YOLO和深度学习的完整实现
  • 学习TS -类型
  • 区块链技术在智能家居中的创新应用探索
  • vscode 文件颜色变绿色
  • “论面向方面的编程技术及其应”,写作框架,软考高级论文,系统架构设计师论文
  • 【IntelliJ IDEA】一篇文章集合所有IDEA的所有设置
  • Spring Boot 3.3 【三】Spring Boot RESTful API 增删改查详细教程
  • UNiapp 微信小程序渐变不生效
  • ue5笔记
  • 渗透测试过程中如何做好个人防护?
  • C++分词工具:Jieba分词
  • [PHP内核探索]PHP中的哈希表
  • 0基础学习移动端适配
  • ESLint简单操作
  • Vue2 SSR 的优化之旅
  • 规范化安全开发 KOA 手脚架
  • 力扣(LeetCode)21
  • 判断客户端类型,Android,iOS,PC
  • 通过几道题目学习二叉搜索树
  • AI又要和人类“对打”,Deepmind宣布《星战Ⅱ》即将开始 ...
  • 关于Kubernetes Dashboard漏洞CVE-2018-18264的修复公告
  • 国内开源镜像站点
  • # 深度解析 Socket 与 WebSocket:原理、区别与应用
  • #1015 : KMP算法
  • (003)SlickEdit Unity的补全
  • (06)金属布线——为半导体注入生命的连接
  • (1)虚拟机的安装与使用,linux系统安装
  • (160)时序收敛--->(10)时序收敛十
  • (2015)JS ES6 必知的十个 特性
  • (27)4.8 习题课
  • (C++哈希表01)
  • (C语言)strcpy与strcpy详解,与模拟实现
  • (补充)IDEA项目结构
  • (二)PySpark3:SparkSQL编程
  • (二十六)Java 数据结构
  • (附源码)计算机毕业设计ssm基于B_S的汽车售后服务管理系统
  • (简单有案例)前端实现主题切换、动态换肤的两种简单方式
  • (每日持续更新)jdk api之FileReader基础、应用、实战
  • (七)Activiti-modeler中文支持
  • (未解决)macOS matplotlib 中文是方框
  • (转) ns2/nam与nam实现相关的文件
  • (转)利用ant在Mac 下自动化打包签名Android程序
  • .NET 5种线程安全集合
  • .NET C# 配置 Options
  • .net core 外观者设计模式 实现,多种支付选择
  • .net refrector
  • .NET/C# 编译期间能确定的相同字符串,在运行期间是相同的实例
  • .NetCore实践篇:分布式监控Zipkin持久化之殇
  • .NetCore项目nginx发布
  • .NET分布式缓存Memcached从入门到实战
  • .NET技术成长路线架构图