如何解决BS4获取python中元素的完整CSS选择器
我正在使用python编写网络刮板,我想使用BS4获得一些元素。我想获得该元素的完整CSS选择器链接
""
如何使用BS4或可以做到这一点的功能?
解决方法
您可以尝试以下代码来打印页面元素的CSS选择器:
from bs4 import BeautifulSoup
def nth_of_type(elem):
count,curr = 0,0
for i,e in enumerate(elem.find_parent().find_all(recursive=False),1):
if e.name == elem.name:
count += 1
if e == elem:
curr = i
return '' if count == 1 else ':nth-of-type({})'.format(curr)
def get_css_selector(elem):
rv = [elem.name + nth_of_type(elem)]
while True:
elem = elem.find_parent()
if not elem or elem.name == '[document]':
return ' > '.join(rv[::-1])
rv.append(elem.name + nth_of_type(elem))
sample_html = '''
<html>
<body>
<div>Hello</div>
<div>World</div>
<div>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
</div>
</body>
</html>
'''
page_soup = BeautifulSoup(sample_html,'html.parser')
elements = page_soup.find('body').find_all()
for element in elements:
css_selector = get_css_selector(element)
txt = page_soup.select_one(css_selector)
print(css_selector)
print(txt)
print('-' * 80)
打印:
html > body > div:nth-of-type(1)
<div>Hello</div>
--------------------------------------------------------------------------------
html > body > div:nth-of-type(2)
<div>World</div>
--------------------------------------------------------------------------------
html > body > div:nth-of-type(3)
<div>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
</div>
--------------------------------------------------------------------------------
html > body > div:nth-of-type(3) > ul
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
--------------------------------------------------------------------------------
html > body > div:nth-of-type(3) > ul > li:nth-of-type(1)
<li>1</li>
--------------------------------------------------------------------------------
html > body > div:nth-of-type(3) > ul > li:nth-of-type(2)
<li>2</li>
--------------------------------------------------------------------------------
html > body > div:nth-of-type(3) > ul > li:nth-of-type(3)
<li>3</li>
--------------------------------------------------------------------------------
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。