如何在html站点中找到一个标记,我知道它与python中的某个模式匹配?

2024-05-29 09:36:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从该站点的冬季/春季/夏季等图表中获取宽度百分比: 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行,它对于每个季节都是唯一的。问题是我得到一个空列表作为输出。我希望我的代码从图表中提取每个季节、白天和夜晚的宽度,这样我就可以确切地知道投票的百分比

你们知道我该怎么办吗

附言: 我还从网站上得到了香水的名字,而且很有效,所以我知道我得到了回复

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

Tags: namehttpsdivcom宽度htmlwww图表
1条回答
网友
1楼 · 发布于 2024-05-29 09:36:09

由于您使用了以下各项,因此会得到一个空列表:

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

但是这个表达式正在寻找一个精确的匹配

但事实上,您希望找到具有style属性的div元素,并且该属性必须包含具有特定值的backgroundCSS属性(在您的示例中为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,它以字节为单位提供响应的内容,而不是可以解析的文本

相关问题 更多 >

    热门问题