python - 如何在 BeautifulSoup 中使用元素的样式定义(例如填充、字体大小等)来抓取元素

标签 python html css web-scraping beautifulsoup

我想使用其样式属性 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/

相关文章:

python - 使用分组依据的 Pandas 百分比变化

html - 自定义 CSS 光标像素化

html - 元素css、html如何分离

jquery - 如何在单击添加类时翻转元素?

CSS font-face - 何时使用多个 src 描述符

python - 如何在 os.listdir 中查找文件和跳过目录

python - 将 API 返回的元素传递给 Pandas DF

python - 如何使用keras获得模型的准确性?

javascript - 悬停时更改 <li> parent 的颜色

javascript - 在移动设备上将文本区域固定在页面底部(带键盘)