用XPath一分钟上手爬虫,良心之作__一蓑烟雨任平生

本文介绍使用XPath进行网页数据抓取的经验分享。通过实例演示XPath如何高效定位并抓取特定信息,对比BeautifulSoup的使用,强调XPath在复杂网页结构中的优势。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

XPath爬取网站信息

之前一直使用BeautifulSoup 爬取各种网站数据

下午研究了下XPath,只能说太牛B

会者不难,难者不会,你会爱上XPath

废话不多说,直接上源码

# encoding=utf-8
import requests
from bs4 import BeautifulSoup  # 用来解析网页
import uuid
import pymysql
import time  # 导入时间隔
import datetime
import threading
from lxml import etree
import os

os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 '
                  'Safari/537.36',
    'Accept-Language': 'zh-CN,zh;q=0.8'
}


def func():
    # 获取现在时间
    now_time = datetime.datetime.now()
    # 获取明天时间
    next_time = now_time + datetime.timedelta(days=+1)
    next_year = next_time.date().year
    next_month = next_time.date().month
    next_day = next_time.date().day
    # 获取明天3点时间
    next_time = datetime.datetime.strptime(str(next_year) + "-" + str(next_month) + "-" + str(next_day) + " 22:00:00",
                                           "%Y-%m-%d %H:%M:%S")
    # # 获取昨天时间
    # last_time = now_time + datetime.timedelta(days=-1)

    # 获取距离明天3点时间,单位为秒
    timer_start_time = (next_time - now_time).total_seconds()
    conn = pymysql.connect(host='127.0.0.1', user='root', passwd='123456', db='zhang', charset='utf8')
    cur = conn.cursor()
    print("数据库已连接")
    for i in range(1, 2):  # 爬取第一页到第3页的数据
        resp = requests.get(
            f"http://www.wbncp.com/PriceQuery.aspx?PageNo={i}&ItemName=牛肉&DateStart=&DateEnd=").content.decode('utf-8')
        et_html = etree.HTML(resp)
        html_data = et_html.xpath('//*/body/form/table[5]/tr/td[3]/table[2]/tr/td[1]/table/tr/td/table[3]/tr')
        # .encode('ISO-8859-1').decode('UTF-8')
        print(html_data)

        for i in html_data:
            print(i.xpath('td')[0].text.strip())
            print(i.xpath('td')[1].text.strip())
            print(i.xpath('td')[2].text.strip())
            print(i.xpath('td')[3].text.strip())
            print(i.xpath('td')[5].text.strip())
            print(i.xpath('td')[7].text.strip())
        # dd = soup.find_all('table')[21].find_all('tr')
        # for ss in dd:  # tr是每一行内容,在所有的行中,遍历每一列的内容
        #     shopDate = ss.findAll('td')[0].text.strip()
        #     print(shopDate)
        # # if str(datetime.datetime.now().day) == str(shopDate.split('-')[2].strip('0')):
        # productId = str(uuid.uuid1())
        # name = ss.findAll('span')[1].text.strip()
        # area = ss.findAll('span')[2].text.strip()
        # price = ss.findAll('span')[3].text.strip('元/斤')
        # unit = '元/斤'
        # sql = "insert into price_data(id,name,area,price,unit,creatime) VALUES (%s,%s,%s,%s,%s,%s)"
        # cur.execute(sql, (productId, name, area, price, unit, shopDate))
        # print("sql已执行")

        print(f"一个页面完事了{i}")
        conn.commit()
        time.sleep(1)  # 防止服务器蹦了,间隔一秒钟
    cur.close()
    conn.close()
    print(timer_start_time)
    timer = threading.Timer(timer_start_time, func)
    timer.start()


# 定时器,参数为(多少时间后执行,单位为秒,执行的方法)
timer = threading.Timer(2, func)
timer.start()

注释加黑的代码是之前的BeautifulSoup 爬取的代码,BeautifulSoup 这个爬取比较简单了一直用find最后来个find_all,然后遍历循环就好了,不过有利有弊

昨天就碰到了难题,一个页面30多个Table,而且class一样,难不成一个一个数去查找你要爬取的数据?

不管你们累不累,我昨天是差点崩溃了,数到21个Table才找到了我想要的数据,然后还学习了一下正则表达式,结果,哎,天生的对运算符有点抵触,学不会,然后就放弃了,然后准备学习下XPath,然后就So Easy!

XPath使用方法

  1. 第一步找到你想要获取的网页,比如你是房地产卖房子的销售,想要做个表格,来统计本市的所有房价,再或者高大上点做个趋势图,看看房价涨势
  2. 就拿安居客来说吧,打开网页
    在这里插入图片描述
  3. 然后按下F12,用鼠标选择到价格的代码位置在这里插入图片描述
  4. 然后鼠标右键,获取XPath在这里插入图片描述
  5. 把我代码里面的路径改改就完事了在这里插入图片描述
  6. 这是价格获取,相同的办法你也可以获取城市,小区,面积,户型所有的数据做成表格

XPath遇到的各种坑

又到总结的时候了,每次写出来的文章都是我踩坑几十次才得到的成果,前人种树后人乘凉,嗯,你们看好啦,以后别犯我的错哈

  1. 第一,这个编码跟BeautifulSoup很大区别,因为BeautifulSoup,解析出来的都是中文,没有乱码,而Xpath解析出来的全是乱码,经过百度几十次各种方法都测试了,找到一种办法成功了获取在这里插入图片描述获取网页的时候首先转码,不然都是乱码

  2. 获取一行数据不要加索引在这里插入图片描述

  3. 在页面上面的在页面解析后是不存在的,那是页面渲染出来的,不要添加不然永远获取的都是空值<tbody>

在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值