Ubuntu爬取网页信息(shell/python爬虫)

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

Ubuntu爬取网页信息

  • 需求: 持续爬取某嵌入式设备配置网页上的状态信息

shell脚本

  • 简单快速, 不用装插件
  • 只能爬取静态内容
  1. curl命令返回整个网页的内容
  2. grep命令抓取其中某些字段
  3. 结合正则表达式可多样查找
  4. 但对于动态内容, 比如对某嵌入式设备配置网页上的一条不断更新的信息, 可能只能爬出来占位符XXXX, 不满足我的需要
#!/bin/bash
while true
do
    # 获取时间戳
    timestamp=$(date +"%Y-%m-%d %T")
    # 先获取网页内容, 再获取内容中带Temperature的一行
    temperature_line=$(curl -s "http://lidar-internal-config.com" | grep "Temperature")
    # 打印出来
    echo "$timestamp $temperature_line" >> log.txt  
    sleep 1
done
# wget和curl差不多效果
# wget -q -O - 192.168.4.5 | grep -o "gps lock\|gps unlock" | awk '{print strftime("%Y-%m-%d %H:%M:%S"), $0}'

python脚本

  • 要安装一些东西, 有点麻烦

  • 可以爬取动态内容, 模仿网页

  • Ubuntu安装selenium

    • pip安装的可能是py2环境下的, 这时要用pip3安装
  • 再安上边链接的步骤安装geckodriver

    • Ubuntu自带火狐, 所以用geckodriver, 会先打开一个网页, 然后在这个网页上刷新.
    • 如果用get打开网页就读取内容, 可能动态内容还没刷出来, 有时还会抓到占位符, 加个延时就行
    • phantomjs不会打开网页, 但对于变化内容还是只能爬出占位符XXXX, 官方好像也放弃这库, 推荐用firefox或chrome
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
import datetime
browser = webdriver.Firefox()
# browser = webdriver.PhantomJS() # 不好用
# 传入地址, 返回要抓取的内容
def Get_Status(address):
    browser.get(address)
    time.sleep(0.2) # 延时等待正常刷新
    # 定位到带GNSS静态字符的位置, 方便抓旁边的动态字符
    elements = browser.find_elements_by_xpath("//*[text()='GNSS']")
    sibling_element = elements[0].find_element_by_xpath(".").
    # 抓取动态内容
    find_element_by_xpath("./following-sibling::*").text
    # print(sibling_element)
    return sibling_element

current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
file_name = "./log/gps_monitor"+current_time+".txt" # 先定好文件名

while True:
    current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") # 每条记录打上时间戳

    Status = Get_Status("你要访问的ip地址")
    
    # 写入log文件内
    with open(file_name,'a') as f:
        f.write("{}: GGG: {} \n".format(current_time, Status))
    time.sleep(10)
browser.close()
阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6