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

相关推荐
2601_962078191 小时前
Python中calendar.weekday用法
python·编程技巧·calendar·日期处理·weekday
2601_962218611 小时前
万象生鲜系统业财一体化底层打通技术自动生成经营账单
大数据·数据库·人工智能·python·算法
2601_966949651 小时前
为什么量化策略需要大量历史股票数据?从回测可信度理解数据规模
开发语言·python·数据分析·pandas·量化交易·股票数据·quantdash
2601_962885721 小时前
如何用 Python 扫描 A 股跳空缺口并统计缺口回补概率?
java·前端·python
李高钢2 小时前
Python FastAPI 框架入门:从零搭建你的第一个高性能 API 服务
数据库·python·fastapi
ocean21032 小时前
2025-2026年Python面试高频知识点洞察
开发语言·python·面试·python八股文
Warson_L3 小时前
Python的OrderedDict
python
隐擎fox3 小时前
高性能网络爬虫架构设计:基于 Python 的长连接复用与分布式会话池调度实践
分布式·python·网络协议·tcp/ip·高并发·网络爬虫、
Warson_L3 小时前
Python的TypedDict
python·langchain·llm
晓窗科技4 小时前
口碑好的AI基座服务商
大数据·人工智能·python