尝试将 CSS 选择器与请求一起使用时出错-HTML

Error while trying to use a CSS selector with requests-HTML

我有一个代码:

from requests_html import HTMLSession

url = 'https://finance.yahoo.com/quote/COMP'
s = HTMLSession()

r = s.get(url)

#Both of these give the same error:

name = r.html.find('h1.D(ib) Fz(18px)', first = True).text
name = r.html.find('h1.D(ib).Fz(18px)', first = True).text

print(name)

这会导致以下错误:

cssselect.parser.SelectorSyntaxError: Expected selector, got <DELIM '(' at 4>

有时在完整的 class 名称中加上一个点,其中 space 有效(请参阅第二个版本的名称)。我不认为我在遵循文档时犯了错误,但在我看来 class 名称中的括号是有问题的。如果我使用 Beautifulsoup,我可以解决这个问题,但我真的很想了解如何在 Requests-HTML.

中解决这个问题

您需要转义括号 :

from requests_html import HTMLSession
url = 'https://finance.yahoo.com/quote/COMP'
s = HTMLSession()

r = s.get(url)

name = r.html.find('h1.D\(ib\)', first=True).text

print(name)

输出:

Compass, Inc. (COMP)