Python 按类查找元素类名称类空间不起作用
我正在尝试使用Python 按类查找元素类名称类空间不起作用,python,selenium,selenium-webdriver,Python,Selenium,Selenium Webdriver,我正在尝试使用按类查找元素\u 代码如下: <a class="yt-simple-endpoint style-scope yt-formatted-string" href="/user/santanderbrasil">Santander Brasil</a> 及 没有一个是有效的 有什么帮助吗?请改用css选择器功能 driver.find_element_by_css_selector("a.yt-simple-endpoint.style-scope.yt-
按类查找元素\u
代码如下:
<a class="yt-simple-endpoint style-scope yt-formatted-string" href="/user/santanderbrasil">Santander Brasil</a>
及
没有一个是有效的
有什么帮助吗?请改用css选择器功能
driver.find_element_by_css_selector("a.yt-simple-endpoint.style-scope.yt-formatted-string")
试试这个
driver.find_element_by_xpath("//div[contains(@class, 'yt-simple-endpoint') and contains(@class, 'style-scope') and contains(@class, 'yt-formatted-string')]"")
我不确定find_元素\u by_xpath方法,因为我在python中没有使用selenium,但不管该函数是什么,选择器都应该起作用
希望这有帮助。这是三个独立的类,通过\u class\u name()查找\u element\u()
只接收一个类作为参数。比如说
driver.find_element_by_class_name('yt-simple-endpoint')
在类之间添加的
表示css\u选择器中的类。您可以使用它通过所有三个类来定位元素使用css\u选择器
driver.find_element_by_css_selector('.yt-simple-endpoint.style-scope.yt-formatted-string')
或者通过xpath
driver.find_element_by_xpath('//a[@class="yt-simple-endpoint style-scope yt-formatted-string"]')
所有这些都适合我(Firefox驱动程序):
请注意,最后一个类名实际上与问题中的第一个类名相同。这是因为Selenium在内部将类名转换为CSS选择器,然后将其用于搜索。如果您想确定特定标记的具体内容,例如仅将
标记与这些类匹配,那么您需要查看CSS选择器和其他选项,如XPath
from selenium import webdriver
driver = webdriver.Firefox()
driver.get("file:///tmp/test.html")
for class_name in 'yt-simple-endpoint', 'yt-formatted-string', 'style-scope', 'yt-simple-endpoint.style-scope.yt-formatted-string':
e = driver.find_element_by_class_name(class_name)
print(e.text)
driver.close()
输出
Santander Brasil
Santander Brasil
Santander Brasil
Santander Brasil
可能是这个印刷品的复制品。但这不是我想要的。我忘了提到我想废弃的内容来自AJAX。我想从youtube主页上显示的第一条横幅上获取内容。这是我在www.youtube.com上检查Elemen时可以看到的代码:如果你在youtube上尝试,它将是一个不同的内容,因为它是一个本地广告。Tudo no应用程序,Tudo na mão!
yt-simple-endpoint
style-scope
yt-formatted-string
yt-simple-endpoint.style-scope.yt-formatted-string
from selenium import webdriver
driver = webdriver.Firefox()
driver.get("file:///tmp/test.html")
for class_name in 'yt-simple-endpoint', 'yt-formatted-string', 'style-scope', 'yt-simple-endpoint.style-scope.yt-formatted-string':
e = driver.find_element_by_class_name(class_name)
print(e.text)
driver.close()
Santander Brasil
Santander Brasil
Santander Brasil
Santander Brasil
<html>
<head><title>Test</title></head>
<body>
<a class="yt-simple-endpoint style-scope yt-formatted-string" href="/user/santanderbrasil">Santander Brasil</a>
</body>
</html>