Python爬虫:下载人生格言
创始人
2024-11-15 05:10:40
0

Python爬虫:下载人生格言

爬取网页

在这里插入图片描述
将这些格言下载存储到本地

代码:
import requests #导入requests库,用于提取网页 from lxml import etree#导入lxml库,用于Xpath数据解析  #请求头 header={ 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36 Edg/127.0.0.0' }#每个浏览器的user-agent不一样,在浏览器中查找  url="http://m.3chongmen.com/renshenggeyan/162.html"#请求网址 res1=requests.get(url=url,headers=header).text html=etree.HTML(res1) title=html.xpath('//div[@class="title"]/h1/text()')[0]#数据解析,提取标题 content=html.xpath('//div[@class="content"]/text()')#数据解析,提取内容 content="".join(content) print(title) print(content) 
运行结果:

在这里插入图片描述

分析:
  • 导入requests库
    requests库是第三方库,要提前安装
    在这里插入图片描述
    输入指令进行安装
pip install requests 

*导入lxml库
输入指令

pip install lxml 
  • headers
    最简单的只用加上user-agent就可以了
    在这里插入图片描述
    鼠标右键,选择”检查“,点击”网络“,ctrl+R刷新页面,点击第一份文件,点击”标头“,滑到最下方查找”User-Agent“,复制到pycharm中即可

  • 数据解析Xpath
    在这里插入图片描述
    用requets获取的源代码如图,想要的信息就在这里面,我们需要提取出来,因此就要用到Xpath进行解析,要先学习一下Xpath语法和lxml库的使用,可以在网上查找相关资料

拓展

将目录下的所有人生格言提取并保存在本地
在这里插入图片描述

代码
import requests from lxml import etree  header={ 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36 Edg/127.0.0.0' }  def spider(url):     res1=requests.get(url=url,headers=header).text     html=etree.HTML(res1)     content=html.xpath('//div[@class="content"]/text()')     content="".join(content)     title=html.xpath('//div[@class="title"]/h1/text()')[0]     return title,content  url1="http://m.3chongmen.com/renshenggeyan" res=requests.get(url=url1,headers=header).text html=etree.HTML(res) links=html.xpath('//ul[@class="list_cnt"]//a[@target="_blank"]/@href')  for link in links:     title,content=spider(link)     with open(f'格言/{title}.txt','w',encoding='utf-8') as f:         f.write(title+'\n\n')         f.write(content) 
运行结果:

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

相关内容

热门资讯

透视法门!pokemomo辅助... 透视法门!pokemomo辅助软件(透视)开挂透视app(哔哩哔哩)1、在pokemomo辅助软件插...
记者爆料"创思维正版... 记者爆料"创思维正版辅助器"其实存在有辅助攻略(了解有挂)-哔哩哔哩1)创思维正版辅助器免费钻石:进...
第2分钟脚本!新玄龙辅助工具,... 第2分钟脚本!新玄龙辅助工具,福建天天开心辅助工具下载(竟然是真的辅助脚本)-哔哩哔哩1、下载好福建...
1分钟秘籍!hhpoker真的... 1分钟秘籍!hhpoker真的有透视吗(透视)竟然是真的有辅助教程(哔哩哔哩)1、hhpoker真的...
重大通报"蜜瓜大厅可... 重大通报"蜜瓜大厅可以装挂吗"一贯存在有辅助技巧(有挂分析)-哔哩哔哩蜜瓜大厅可以装挂吗是不是有人用...
透视办法!poker worl... 透视办法!poker world辅助器(透视)开挂透视工具(哔哩哔哩);1、poker world辅...
第五分钟脚本!微信超级三加一辅... 第五分钟脚本!微信超级三加一辅助,小程序牵手跑得有外开挂吗(切实真的有辅助app)-哔哩哔哩1、这是...
三分钟项目!wepoker透视... 三分钟项目!wepoker透视是真的吗(透视)总是存在有辅助开挂(哔哩哔哩)1、操作简单,无需wep...
盘点几款"情怀游戏字... 盘点几款"情怀游戏字牌辅助"都是是有辅助攻略(有挂方略)-哔哩哔哩1、情怀游戏字牌辅助辅助器安装包、...
透视课程!wepoker俱乐部... 透视课程!wepoker俱乐部辅助(透视)开挂透视辅助器(哔哩哔哩)暗藏猫腻,小编详细说明wepok...