【发布时间】:2020-03-21 18:34:06
【问题描述】:
我正在尝试通过使用 Python Selenium 和 Chrome 驱动程序 来获取跨度标记中的 Instagram 帐户的发布数量,这是html代码:
<!doctype html>
<html lang="fr" class="js logged-in client-root js-focus-visible sDN5V">
<head>-</head>
<body class style>
<div id="react-root"> == 50
<form enctype^murtipart/form-data" method="POST" role="presentation">_</form>
<section class=”_9eogI E3X2T">
<div></div>
<main class="SCxLW o64aR " role=”main">
<div class=”v9tJq AAaSh VfzDr">
<header class=" HVbuG">_</header>
► <div class="-vDIg">_</div>
► <div class="_4bSq7">_</div>
▼ <ul class=” _3dEHb">
▼ <li class=” LH36I">
▼ <span class=" _81NM2">
<span class="g47SY 10XF2">6 588</span>
"publications"
</span>
</li>
Python 代码
def get_publications_number(self, user):
self.nav_user(user)
sleep(16)
publication = self.driver.find_element_by_xpath('//div[contains(id,"react-root")]/section/main/div/ul/li[1]/span/span')
错误信息
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element:
{"method":"xpath","selector":"//div[contains(id,"react-root")]/section/main/div/ul/li[1]/span/span"}
(Session info: chrome=80.0.3987.149)
重要提示:
这个 xpath 是从 Chrome 元素检查器粘贴的,所以我认为不是问题所在。当我输入self.driver.find_elements_by_xpath()(带有's')时不会出现错误,如果我这样做:
for value in publication:
print(value.text)
也不会有错误,但不会打印任何内容
所以问题是:
为什么我在 Xpath 存在时收到此错误?
【问题讨论】:
-
你做过调试吗?如何从 XPath 中逐个删除元素并每次检查结果?另外,
'//div[contains(id,"react-root")]'不应该只是'//div[@id="react-root")]'吗? -
我想过,但是这个路径是由 Chrome 的元素检查器给出的,所以路径实际上不是问题
标签: python python-3.x selenium web-scraping selenium-chromedriver