字体反爬案例二

该文章演示了如何使用Python的Selenium库打开浏览器,获取CSS文件内容,通过正则表达式解析评分映射,然后使用PyQuery解析网页源码,提取电影评分。在CSS文件中,评分被编码为图标类名,通过解码映射关系得到真实评分,并显示电影名称与分类。
摘要由CSDN通过智能技术生成
from selenium import webdriver
from pyquery import PyQuery as pq
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
import re
import requests

# css文件与评分结果映射关系,需解析后转换
url = 'https://antispider4.scrape.center/css/app.654ba59e.css'
# 使用requests提取CSS文件内容,再用正则表达式进行文本匹配
response = requests.get(url)
# CSS样式: .icon-789:before{content:"9"}  提取得到两个group,第一个是789,第二个是9

pattern = re.compile('.icon-(.*?):before\{content:"(.*?)"\}')
# re.findall():函数返回包含所有匹配项的列表。返回response.text中所有与pattern相匹配的全部字串,返回形式为数组。
results = re.findall(pattern, response.text)
# 结果是由很多二元组组成的列表,遍历列表,将其赋值成字典即可
icon_map = {item[0]: item[1] for item in results}

# 解析源码,接收一个PyQuery对象item,对应一个电影条目
def parse_score(item):
    # 提取该item中所有带icon这个class节点
    elements = item('.icon')
    icon_values = []
    # 遍历这些节点,从class属性里提取对应的icon代号,如icon-789
    for element in elements.items():
        class_name = (element.attr('class'))
        # 将提取的代码赋值给icon_key
        icon_key = re.search('icon-(\d+)', class_name).group(1)
        # 使用icon_key从icon_map中查找对应的真实值,并赋值给icon_value
        icon_value = icon_map.get(icon_key)
        icon_values.append(icon_value)
    # 最后将icon_value 拼合成一个字符串返回
    return ''.join(icon_values)

# 开启浏览器,使用Chrom类生成一个webdriver对象并赋值为browser变量
browser = webdriver.Chrome()
browser.get('https://antispider4.scrape.center/')
# 显式等待浏览器10S(WebDriverWait对象,配置页面加载的最长等待时间)
WebDriverWait(browser, 10).until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, '.item')))
# 获取页面源码
html = browser.page_source
# PyQuery HTML 解析库
doc = pq(html)
# 传入 CSS 选择器
items = doc('.item')
for item in items.items():
    # 电影名称
    name = item('.name').text()
    # 剧情
    categories = [o.text() for o in item('.categories button').items()]
    # 解析源码,获取评分结果
    score = parse_score(item)
    print(f'name: {name} categories: {categories} score:{score}')
browser.close()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值