我正在使用python编写网络刮板,我想使用BS4获得一些元素。我想获得该元素的完整CSS选择器链接
""
如何使用BS4或可以做到这一点的功能?
答案 0 :(得分:0)
您可以尝试以下代码来打印页面元素的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>
--------------------------------------------------------------------------------