python--常用简单功能

os函数获取上层目录

python 复制代码
# 获取当前目录
print(os.path.abspath(os.path.dirname(__file__)))
# 获取上级目录
print(os.path.abspath(os.path.dirname(os.path.dirname(__file__))))
print(os.path.abspath(os.path.dirname(os.getcwd())))
print(os.path.abspath(os.path.join(os.getcwd(), "..")))
# 获取上上级目录
print(os.path.abspath(os.path.join(os.getcwd(), "../..")))

中文转为 url 编码

python 复制代码
from urllib.parse import quote
print(quote("xxxx"))

二次 xpath 提取

html 复制代码
<div id="main">
      <div  id="main1">
               <ul>
                   <li>1</li>
                   <li>2</li>
                   <li>3</li>
                   <li>4</li>
           </ul>
       </div>
   </div>
python 复制代码
div = html.xpath("//div[@id='main']")
li = div.xpath("div[@id='main1']/li")

scrapy在爬虫文件中导入 items 文件中的类

python 复制代码
"""items.py"""
class FirstItem(scrapy.Item):
    shopName = scrapy.Field()
    start = scrapy.Field()
    commentNumber = scrapy.Field()
    avgPrice = scrapy.Field()
    shopType = scrapy.Field()
    shopAddress = scrapy.Field()
    isGroupBuy = scrapy.Field()
    groupBuyContent = scrapy.Field()
python 复制代码
"""spider.py"""
from ..items import FirstItem

创建 Scrapy 项目

创建项目的命令:

scrapy startproject MySpider

cd MySpider

在已有 scrapy 项目下创建爬虫:
scrapy genspider example example.com

相关推荐
金銀銅鐵1 天前
[Python] 从《千字文》中随机挑选汉字
后端·python
cup111 天前
[技术复盘] Windows Python 打包实战:Nuitka 环境踩坑总结与 CI 自动化构建全指南
python·ai·环境变量·ci·nuitka·skill
aqi001 天前
15天学会AI应用开发(七)有了大模型为什么还要引入RAG
人工智能·python·大模型·ai编程·ai应用
金銀銅鐵1 天前
用 Python 实现 Take-Away 游戏
python·游戏
copyer_xyf1 天前
Agent 流程编排
后端·python·agent
copyer_xyf1 天前
Agent RAG
后端·python·agent
copyer_xyf1 天前
【RAG】向量数据库:milvus
后端·python·agent
copyer_xyf1 天前
Agent 记忆管理
后端·python·agent
星云穿梭2 天前
用Python写一个带图形界面的学生管理系统——完整教程
python