Python爬虫:下载人生格言

Python爬虫:下载人生格言

爬取网页

将这些格言下载存储到本地

代码:
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库的使用,可以在网上查找相关资料

拓展

将目录下的所有人生格言提取并保存在本地

代码
python 复制代码
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)
运行结果:


相关推荐
R-sz1 分钟前
导出word并且插入图片
开发语言·c#·word
CodeWithMe1 分钟前
【读书笔记】《C++ Software Design》第一章《The Art of Software Design》
开发语言·c++
脑袋大大的19 分钟前
判断当前是否为钉钉环境
开发语言·前端·javascript·钉钉·企业应用开发
运器12321 分钟前
【一起来学AI大模型】PyTorch DataLoader 实战指南
大数据·人工智能·pytorch·python·深度学习·ai·ai编程
音元系统24 分钟前
Copilot 在 VS Code 中的免费替代方案
python·github·copilot
超龄超能程序猿36 分钟前
(5)机器学习小白入门 YOLOv:数据需求与图像不足应对策略
人工智能·python·机器学习·numpy·pandas·scipy
Wy. Lsy1 小时前
Kotlin基础学习记录
开发语言·学习·kotlin
Tanecious.1 小时前
C++--红黑树
开发语言·c++
Top`1 小时前
Java 泛型 (Generics)
java·开发语言·windows
爱吃土豆的马铃薯ㅤㅤㅤㅤㅤㅤㅤㅤㅤ2 小时前
如何使用Java WebSocket API实现客户端和服务器端的通信?
java·开发语言·websocket