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)
相关推荐
合作小小程序员小小店25 分钟前
SDN安全开发环境中常见的框架,工具,第三方库,mininet常见指令介绍
python·安全·生成对抗网络·网络安全·网络攻击模型
后台开发者Ethan28 分钟前
Python需要了解的一些知识
开发语言·人工智能·python
yzzzzzzzzzzzzzzzzz34 分钟前
HTML 常用标签介绍
前端·html
北京_宏哥37 分钟前
Python零基础从入门到精通详细教程11 - python数据类型之数字(Number)-浮点型(float)详解
前端·python·面试
盼小辉丶1 小时前
PyTorch生成式人工智能——使用MusicGen生成音乐
pytorch·python·深度学习·生成模型
常利兵1 小时前
Kotlin作用域函数全解:run/with/apply/let/also与this/it的魔法对决
android·开发语言·kotlin
幼稚园的山代王1 小时前
Kotlin-基础语法练习一
android·开发语言·kotlin
重生成为编程大王2 小时前
Java ConcurrentHashMap 深度解析
java·开发语言
老虎06272 小时前
JavaWeb前端(HTML,CSS具体案例)
前端·css·html
tanyongxi662 小时前
C++ 特殊类设计与单例模式解析
java·开发语言·数据结构·c++·算法·单例模式