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

相关推荐
databook3 小时前
Manim实现闪光轨迹特效
后端·python·动效
Juchecar5 小时前
解惑:NumPy 中 ndarray.ndim 到底是什么?
python
用户8356290780515 小时前
Python 删除 Excel 工作表中的空白行列
后端·python
Json_5 小时前
使用python-fastApi框架开发一个学校宿舍管理系统-前后端分离项目
后端·python·fastapi
数据智能老司机11 小时前
精通 Python 设计模式——分布式系统模式
python·设计模式·架构
数据智能老司机12 小时前
精通 Python 设计模式——并发与异步模式
python·设计模式·编程语言
数据智能老司机12 小时前
精通 Python 设计模式——测试模式
python·设计模式·架构
数据智能老司机12 小时前
精通 Python 设计模式——性能模式
python·设计模式·架构
c8i13 小时前
drf初步梳理
python·django
每日AI新事件13 小时前
python的异步函数
python