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)
运行结果:


相关推荐
同学小张38 分钟前
【端侧AI 与 C++】1. llama.cpp源码编译与本地运行
开发语言·c++·aigc·llama·agi·ai-native
DanCheng-studio1 小时前
网安毕业设计简单的方向答疑
python·毕业设计·毕设
深蓝电商API1 小时前
爬虫界的 “核武器”:Splash + Scrapy 动态渲染终极方案
爬虫·scrapy·splash
踢球的打工仔2 小时前
PHP面向对象(7)
android·开发语言·php
轻抚酸~2 小时前
KNN(K近邻算法)-python实现
python·算法·近邻算法
独行soc3 小时前
2025年渗透测试面试题总结-264(题目+回答)
网络·python·安全·web安全·网络安全·渗透测试·安全狮
汤姆yu4 小时前
基于python的外卖配送及数据分析系统
开发语言·python·外卖分析
Yue丶越4 小时前
【C语言】字符函数和字符串函数
c语言·开发语言·算法
如何原谅奋力过但无声4 小时前
TensorFlow 1.x常用函数总结(持续更新)
人工智能·python·tensorflow
翔云 OCR API4 小时前
人脸识别API开发者对接代码示例
开发语言·人工智能·python·计算机视觉·ocr