我想使用其样式属性 padding-left: 16px
提取 div,如以下 Python 代码所示。但显然它不起作用。我知道如何使用元素的类、id 或标签来提取元素。有没有办法使用 style 属性来做同样的事情?
from bs4 import BeautifulSoup
f = open("C:\Users\admin\Documents\GitHub\RedditCrawler\new.html");
soup = BeautifulSoup(f);
f.close();
hr2 = soup.find('div', style={"padding-left":"16px"});
print(hr2);
以下是我尝试从 html 文件中提取的 div:
<html>
<div style="padding-left:16px;">This is the deal</div>
</html>
最佳答案
使用 CSS 选择器获取 div 元素。
soup.select_one('div[style="padding-left:16px;"]')
代码:
from bs4 import BeautifulSoup
html='''<html>
<div style="padding-left:16px;">This is the deal</div>
</html>'''
soup=BeautifulSoup(html,'html.parser')
#To get the element
print(soup.select_one('div[style="padding-left:16px;"]'))
#To get the text
print(soup.select_one('div[style="padding-left:16px;"]').text)
#To get the style value
print(soup.select_one('div[style="padding-left:16px;"]')['style'])
输出:
<div style="padding-left:16px;">This is the deal</div>
This is the deal
padding-left:16px;
关于python - 如何在 BeautifulSoup 中使用元素的样式定义(例如填充、字体大小等)来抓取元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59461796/