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)
相关推荐
emplace_back1 小时前
C# 集合表达式和展开运算符 (..) 详解
开发语言·windows·c#
jz_ddk1 小时前
[学习] C语言数学库函数背后的故事:`double erf(double x)`
c语言·开发语言·学习
萧曵 丶1 小时前
Rust 所有权系统:深入浅出指南
开发语言·后端·rust
xiaolang_8616_wjl1 小时前
c++文字游戏_闯关打怪2.0(开源)
开发语言·c++·开源
收破烂的小熊猫~1 小时前
《Java修仙传:从凡胎到码帝》第四章:设计模式破万法
java·开发语言·设计模式
蹦蹦跳跳真可爱5892 小时前
Python----OpenCV(图像増强——高通滤波(索贝尔算子、沙尔算子、拉普拉斯算子),图像浮雕与特效处理)
人工智能·python·opencv·计算机视觉
nananaij2 小时前
【Python进阶篇 面向对象程序设计(3) 继承】
开发语言·python·神经网络·pycharm
雷羿 LexChien2 小时前
从 Prompt 管理到人格稳定:探索 Cursor AI 编辑器如何赋能 Prompt 工程与人格风格设计(上)
人工智能·python·llm·编辑器·prompt
阿蒙Amon2 小时前
为什么 12 版仍封神?《C# 高级编程》:从.NET 5 到实战架构,进阶者绕不开的必修课
开发语言·c#