remote_command

本文介绍了一种使用Python的requests库和BeautifulSoup库从百度贴吧抓取帖子内容的方法。通过设置请求头,发送GET请求获取网页源代码,再利用BeautifulSoup解析网页,找到并打印出特定类别的div元素,最后提取并输出所需的内容。
import requests
from bs4 import BeautifulSoup
import json
def get_response():
    URL = "https://tieba.baidu.com/p/6372327480"
    headers={"User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36"}
    r = requests.get(URL,headers=headers)
    # print(r.text)
    soup = BeautifulSoup(r.text,'lxml')
    match = soup.find_all(name="div",attrs={"class":"d_post_content j_d_post_content"})
    print(match)
    print(match[-1])
    return str(match[-1])

def get_command(class_content):
    string1 = r'style="display:;">'
    string2 = r'</div>'
    content = class_content.split(string1)[-1].split(string2)[0].strip()
    print(content)
    return content

if __name__ == '__main__':
    print("="*20)
    class_content =get_response()
    content = get_command(class_content)
    command = json.loads(content)
    print(command)

 

你当前的代码会将远程执行的结果写入一个固定的本地文件 `remote_data_path`,这在并发或多次运行时容易造成冲突或覆盖。 --- ### ✅ 优化目标 1. **让 `remote_data_path` 唯一化** → 加时间戳后缀 2. **使用完后自动删除文件** → 确保不残留临时文件 3. 可选:使用 `tempfile` 更安全(但你希望保留路径可控 + 时间命名) --- ### ✅ 改进后的代码(带时间戳命名 + 自动删除) ```python import os from datetime import datetime # 构建唯一文件名:例如 'remote_map_version_20250405_142301.txt' timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") unique_filename = f"remote_map_version_{timestamp}.txt" remote_data_path = os.path.join(os.getcwd(), unique_filename) # 或指定其他目录 try: # 执行远程命令获取数据 result = raspberry_client.execute_remote_command(recorded_msg_cmd) logger.info(f'将查询到的零件版本信息写入本地唯一文件: {remote_data_path}') with open(remote_data_path, 'w', encoding='utf-8') as file: file.write(result) print(f"内容已成功保存到 {remote_data_path}") logger.info(f'提取文件中的版本信息: {remote_data_path}') data = [] with open(remote_data_path, 'r', encoding='utf-8') as file: file_content = file.read() lines = file_content.splitlines() for line in lines[3:]: # 跳过前3行表头和分隔线 if line and not line.startswith('---'): parts = line.split('|') if len(parts) >= 3: part_name = remove_escape_sequences(parts[0].strip()) version = remove_escape_sequences(parts[2].strip()) data.append([part_name, version]) # ✅ 此处可以继续处理 data ... finally: # ⚠️ 确保无论成功或异常,最后都删除临时文件 if os.path.exists(remote_data_path): os.remove(remote_data_path) logger.debug(f"临时文件已删除: {remote_data_path}") ``` --- ### 🔍 关键改进点说明 | 功能 | 实现方式 | |------|----------| | 🕒 **唯一文件名** | 使用 `datetime.now().strftime("%Y%m%d_%H%M%S")` 添加高精度时间戳 | | 💾 **路径可控** | `os.path.join(os.getcwd(), ...)` 可替换为任意目录 | | ❌ **自动清理** | 使用 `try...finally`,确保 `os.remove()` 必定执行 | | 🧼 **避免残留** | 即使程序出错(如解析异常),文件也会被删除 | --- ### ✅ 示例生成的文件名 ``` remote_map_version_20250405_142301.txt remote_map_version_20250405_142302.txt ... ``` 每秒最多一个,保证唯一性。如果你需要更高精度(毫秒级),可以用: ```python timestamp = datetime.now().strftime("%Y%m%d_%H%M%S_%f")[:-3] # 毫秒 ``` --- ### ✅ 替代方案建议(更安全):使用 `tempfile.NamedTemporaryFile` ```python import tempfile with tempfile.NamedTemporaryFile(mode='w+', encoding='utf-8', suffix='.txt', delete=False) as tmp_file: tmp_path = tmp_file.name tmp_file.write(result) # 后续读取... # 最后记得 os.remove(tmp_path) ``` 但因为你可能希望“看到”文件名便于调试,所以时间戳命名更合适。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值