首页 > 解决方案 > 使用 BS4 解析 ::before

问题描述

尝试解析网页。在页面 html中面对::before

url = 'https://kant-sport.ru/sports/skiing/svobodnoe-katanie/'

# Getting whole page
page = get(url)

# Making soup
soup = BS(page.content, 'html.parser')

# Getting table
table = soup.select('.new-tables-content')[0]

# Getting table's rows and getting rid of first unneeded row
rows = table.select('.new-tables-content-row')[1:]

然后我需要得到'x'符号

# Getting 'x' symbol by class
print(rows[0].find(class_="new-tables-content-col::before"))

输出

None

并使用选择方法(css 选择器

# Getting 'x' symbol by css
print(rows[0].select('.new-tables-content-row:not(.new-tables-content-header) .new-tables-content-col:last-child:before'))

输出

Traceback (most recent call last):
  File "E:/Coding/PycharmProjects/kant-monitoring-bot/parser.py", line 36, in <module>
    print(rows[0].select('.new-tables-content-row:not(.new-tables-content-header) .new-tables-content-col:last-child:before'))
  File "E:\Coding\PycharmProjects\kant-monitoring-bot\venv\lib\site-packages\bs4\element.py", line 1869, in select
    results = soupsieve.select(selector, self, namespaces, limit, **kwargs)
  File "E:\Coding\PycharmProjects\kant-monitoring-bot\venv\lib\site-packages\soupsieve\__init__.py", line 98, in select
    return compile(select, namespaces, flags, **kwargs).select(tag, limit)
  File "E:\Coding\PycharmProjects\kant-monitoring-bot\venv\lib\site-packages\soupsieve\__init__.py", line 62, in compile
    return cp._cached_css_compile(pattern, namespaces, custom, flags)
  File "E:\Coding\PycharmProjects\kant-monitoring-bot\venv\lib\site-packages\soupsieve\css_parser.py", line 208, in _cached_css_compile
    CSSParser(pattern, custom=custom_selectors, flags=flags).process_selectors(),
  File "E:\Coding\PycharmProjects\kant-monitoring-bot\venv\lib\site-packages\soupsieve\css_parser.py", line 1043, in process_selectors
    return self.parse_selectors(self.selector_iter(self.pattern), index, flags)
  File "E:\Coding\PycharmProjects\kant-monitoring-bot\venv\lib\site-packages\soupsieve\css_parser.py", line 902, in parse_selectors
    has_selector, is_html = self.parse_pseudo_class(sel, m, has_selector, iselector, is_html)
  File "E:\Coding\PycharmProjects\kant-monitoring-bot\venv\lib\site-packages\soupsieve\css_parser.py", line 640, in parse_pseudo_class
    "'{}' pseudo-class is not implemented at this time".format(pseudo)
NotImplementedError: ':before' pseudo-class is not implemented at this time

Process finished with exit code 1

如何使用::before::after正确解析元素

标签: pythonparsingbeautifulsouprequest

解决方案


作为soupsieve(BeautifulSoup中使用的选择库)的作者,我可以回答这个问题。您不能用于::before解析伪元素。

一方面,伪元素不是真正的元素。浏览器在渲染源代码时可能会创建这些伪元素,但它们不存在于源代码中,仅存在于渲染的实现中。BeautifulSoup 不渲染 HTML,它只是解析它;因此,没有伪元素。如果您打印 HTML 源代码(在使用 BeautifulSoup 解析之后),您会发现::before文档结构中没有任何元素。

此外,soupsieve 目前不支持任何伪元素选择器。它支持许多选择器和大量的伪类,但它根本不支持伪元素。


推荐阅读