【问题标题】:How can I find a tag in html site that I know it matches a certain pattern in python?如何在 html 站点中找到我知道它与 python 中的特定模式匹配的标签?
【发布时间】:2021-05-18 07:16:29
【问题描述】:

我想从本网站的冬季/春季/夏季等图表中获取宽度百分比: https://www.fragrantica.com/perfume/Christian-Dior/Sauvage-Eau-de-Parfum-48100.html

例如,对于冬季,我想在页面元素中找到这一行:

<div style="border-radius: 0.2rem; height: 0.3rem; background: rgb(120, 214, 240); width: 90.3491%; opacity: 1;"></div>

我已经尝试了以下

res = requests.get("https://www.fragrantica.com/perfume/Christian-Dior/Sauvage-Eau-de-Parfum- 
                    48100.html", headers={'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) 
                                           AppleWebKit/537.36 (KHTML, like Gecko),
                                           Chrome/88.0.4324.150 Safari/537.36'}
soup = BeautifulSoup(res.content, 'html.parser')
winter_row = soup.select('div[style="rgb(120, 214, 240)"]')
print(winter_row) 

我想找到使用 RGB 的特定 html 行对于每个季节都是唯一的。问题是我得到一个空列表作为输出。我希望我的代码从图表中提取每个季节、白天和黑夜的宽度,以便我确切地知道投票的百分比。

你们知道我该怎么做吗?

PS: 我还从网站上获得了香水的名称,并且它有效,所以我知道我得到了回应。

name_row = soup.select('#toptop')[0]
name = name_row.getText().replace('\n', '')

【问题讨论】:

    标签: python html css beautifulsoup python-requests


    【解决方案1】:

    你得到一个空列表,因为你使用:

    soup.select('div[style="rgb(120, 214, 240)"]')

    但是这个表达式正在寻找完全匹配。

    但实际上您想找到具有style 属性的div 元素,并且此属性必须包含具有特定值的background CSS 属性(在您的示例中为rgb(120, 214, 240))。 所以你必须使用这个 CSS 属性选择器 语法:

    soup.select("[style*='background: rgb(120, 214, 240)']")
    

    例子:

    htmlpage = """<!doctype html>
    <html lang="en">
      <head>
        <title>Title</title>
      </head>
      <body>
        <div style="border-radius: 0.2rem; height: 0.3rem; background: rgb(120, 214, 240); width: 90.3491%; opacity: 1;"></div>
      </body>
    </html>"""
    
    soup = BeautifulSoup(htmlpage, 'html.parser')
    extracted = soup.select("[style*='background: rgb(120, 214, 240)']")
    
    print(extracted)
    

    输出:

    [<div style="border-radius: 0.2rem; height: 0.3rem; background: rgb(120, 214, 240); width: 90.3491%; opacity: 1;"></div>]
    

    您应该使用res.text 而不是res.content,它以字节为单位提供响应内容,而不是可以解析的文本。

    【讨论】:

    • 我仍然得到一个空列表:(
    猜你喜欢
    • 1970-01-01
    • 2020-12-04
    • 2014-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 2015-09-24
    相关资源
    最近更新 更多