Skip to main content
 首页 » 编程设计

python之使用 Python 匹配 HTML 解析中的输入文本

2025年01月19日10cloudgamer

我认为只要设置“text=size”就会得到我需要的值。也许我想念理解?我做错了什么?

import requests, re, json, time, sys, os,webbrowser 
import subprocess as s 
from bs4 import BeautifulSoup as bs 
global size 
 
size = "Medium" 
 
'''html  = <option selected="selected" data-sku="51728-003" value="660654030868">Medium - $138.00 USD</option>''' 
 
url = "https://us.octobersveryown.com/collections/shop-all/products/varsity-ovo-polartec-half-zip-pullover-black" 
 
def getStuff(): 
    print ('') 
session = requests.session() 
response = session.get(url) 
soup = bs(response.text, 'html.parser') 
prod_name = soup.find('h1',{'itemprop':'name'}).text 
price = soup.find('span',{'id':'ProductPrice'}).text 
variant = soup.find(text=size).findPrevious('value').text 
#variant ="notworking" 
print("\nProd Name: "+prod_name) 
print("\nPrice: "+price) 
print("\nMatching Variant Value: "+variant) 
 
getStuff() 

我的错误是

Traceback (most recent call last): 
  File "trythis.py", line 20, in <module> 
    variant = soup.find(text=size).findPrevious('value').text 
AttributeError: 'NoneType' object has no attribute 'text' 

请您参考如下方法:

这是一个有趣的问题。由于您正在尝试匹配 option 标签文本中的单词并从该标签获取属性,因此我会这样做:

import requests, re, json, time, sys, os,webbrowser 
import subprocess as s 
from bs4 import BeautifulSoup as bs 
global size 
 
size = "Medium" 
 
html  = """<option selected="selected" data-sku="51728-003" value="660654030868">Medium - $138.00 USD</option>""" 
 
url = "https://us.octobersveryown.com/collections/shop-all/products/varsity-ovo-polartec-half-zip-pullover-black" 
 
def getStuff(): 
    print ('') 
    session = requests.session() 
    response = session.get(url) 
    soup = bs(response.text, 'html.parser') 
    prod_name = soup.find('h1',{'itemprop':'name'}).text 
    price = soup.find('span',{'id':'ProductPrice'}).text 
    #variant = soup.find(text=size).findPrevious('value').text 
    def get_option(size): 
        options = soup.find_all('option') 
        target_option = [o for o in options if size in o.text][0] 
        value = target_option['value'] 
        return value 
    def get_options_and_values(): 
        option_dic = {} 
        options = soup.find_all('option') 
        for o in options: 
            try: 
                option_dic[o.text.split('-')[0].strip()] = int(o['value']) 
            except: 
                pass 
        return option_dic 
    print(get_options_and_values()) 
    print("\nProd Name: "+prod_name) 
    print("\nPrice: "+price.strip()) 
    variant = get_option(size) 
    print("\nMatching Variant Value: "+variant) 
 
getStuff() 

这给了我:

{'Medium': 660654030868, 'Large': 660654063636} 
 
Prod Name: VARSITY OVO POLARTEC® HALF-ZIP PULLOVER - BLACK 
 
Price: $138.00 
 
Matching Variant Value: 660654030868 

这将允许您轻松更改您想要的尺寸。这有意义吗?