Python提取HTML里的内容并解析——提取总页面数

通过所检索的url地址,找到总页数一栏,如:<span class="sui-pagination__total" tabindex="0" aria-label="Total 40 Pages">Total 40 Pages</span>,抽取总页数。

正则表达式提取总页数

考虑页数是个整数,可以用\d+表达式匹配当中的数字,代码如下:

python 复制代码
import re

page_count = 0
regex = r'\d+'
pagination_total_str = 'Total 40 Pages'
# 查找出对应的数字数组
match_arr = re.findall(regex, pagination_total_str)
# 第一个数字就是总页数
if match_arr[0].isdigit():
    page_count = eval(match_arr[0])
print(page_count)    

抽取页面的总页数信息

一开始想应用requests搭配BeautifulSoap提取页面数据,获得商品总数,但希音网站通过ajax手段加载完整页面,故不得不使用selenium+PhantomJS,完整加载页面后一次性获取全部内容再进行分析。

python 复制代码
# import requests
from selenium import webdriver
from bs4 import BeautifulSoup
import re

url = 'https://us.shein.com/pdsearch/shirt%20man/?ici=s1`RecentSearch`shirt%20man`_fb`d0`PageHome&search_source=1&search_type=all&source=historyWord&src_identifier=st%3D5%60sc%3Dshirt%20man%60sr%3D0%60ps%3D1&src_identifier_pre_search=&src_module=search&src_tab_page_id=page_home1720763711938'
# response = requests.get(url)
# content_text = ''
# page_count = 0
# if response.status_code == 200:
#     content_text = response.text
# if content_text:
#     soup = BeautifulSoup(content_text, "html.parser")
#     span = soup.find_all("span")
#     print(span)

def get_html(url):
    # driver = webdriver.PhantomJS(executable_path='./phantomjs-2.1.1-windows/bin/phantomjs')  # phantomjs的绝对路径,现在新版本的selenium废弃了此方法,需要2.48版
    driver = webdriver.Edge()
    driver.get(url)
    return driver.page_source

def get_total_page(html, regex=r'\d+'):
    page_count = 0
    soup = BeautifulSoup(html, 'html.parser')  # 用HTML解析网址
    tag = soup.find_all('span', attrs={'class': 'sui-pagination__total'})
    pagination_total_str = tag[0].decode_contents()
    # 查找出对应的数字数组
    match_arr = re.findall(regex, pagination_total_str)
    # 第一个数字就是总页数
    if match_arr[0].isdigit():
        page_count = eval(match_arr[0])
    return page_count

html = get_html(url)
get_total_page(html)
相关推荐
2601_967979127 小时前
初学者必知的Python中优雅的用法
python·枚举·初学者·优雅用法·字典解析
FRing037 小时前
vue2干货总结12(loading效果、全局前置导航守卫、搜索历史管理)
开发语言·前端·javascript·vue.js·vue2
wefg17 小时前
【项目】C++ 基于 Vibe Coding 的 OJ 平台
开发语言·c++
AI创界者9 小时前
Python 进阶实战(五十八章):配置热更新、优雅停机排空与高并发压测方案
人工智能·python·aigc
琳少_11 小时前
java程序设计笔记
java·开发语言·数据库·笔记
2601_9679873712 小时前
python网络工程师自动化运维课程
python·正则表达式·网络工程师·模块·自动化运维
吴凡wudianmei13 小时前
给 LLM 套输出契约:校验失败怎么把错误回灌给模型
python·llm·agent
Helix25013 小时前
JDK高频报错速查手册:javac不是内部命令、内存溢出、版本不兼容等12类问题解决方法
java·开发语言·内存溢出·java异常处理·jdk版本兼容·jdk报错·javac报错
祺曦13 小时前
复现连续手语识别项目
python·手语识别·复现项目·corrnet
江润舟14 小时前
万物|炼器:从零手搓工业级旋转目标检测网络·卷7 —— OBB检测头与DFL解码(三)
人工智能·python·深度学习