在Python中找不到元素

2024-06-28 11:02:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图进入曼联的主场,但不可能进入。 .Here is the website page

下面是HTML页面的一段代码:

<div id="g_1_l2dtbMED" title="Click for match detail!" class="event__match event__match--static event__match--last event__match--oneLine"><div class="event__time">04.10. 17:30</div><div class="event__participant event__participant--home"><svg class="card___2ip_DLm icon--redCard icon--redCard-first icon--redCard-last"><title></title><use xlink:href="/res/_fs/build/symbols.f1bc6b2.svg#card"></use></svg>Manchester Utd</div><div class="event__scores fontBold"><span>1</span>&nbsp;-&nbsp;<span>6</span></div><div class="event__participant event__participant--away fontBold">Tottenham</div><div class="event__part">(1&nbsp;-&nbsp;4)</div><span class="wld wld--l" title="Loss">L</span></div>

我要搜索解析的结果是'L',位于应答器<span>

下面是我为尝试解析它所做的代码:

driver = webdriver.Chrome()
url = "https://www.flashscore.com/team/manchester-united/ppjDR086/results/"
driver.get(url)

Team = 'manchester Utd'
results = WebDriverWait(driver, 20).until(EC.find_elements((By.XPATH,"//div[@class='event__participant--home' and contains(text(),'"+ Team +"')]//ancestor::div/span")))
print(len(results))

但这在20秒后给我抛出了一个异常“TimeoutException”,这是搜索的时间限制


Tags: 代码svgdiveventtitlematchdriverresults
2条回答

您正在查找的定位器是

//div[contains(@class,'event__participant home')][text()='Manchester Utd']//following-sibling::span[1]
^ find a DIV that contains the class indicating a home game
                                                  ^ that also contains the team name
                                                                           ^ then find the first sibling SPAN that follows

该定位器将仅为家庭游戏查找包含L、W、D等的元素

如果要等待元素,则需要等待可见,而不是存在。存在是指元素仅在DOM中,但不一定可见。如果要从页面上删除文本,则需要等待可见。您可以使用EC.visibility_of_all_elements_located()来实现这一点。见the docs。如果在页面存在但不可见时尝试刮除页面,则会引发异常

您的更新代码如下

driver = webdriver.Chrome()
url = "https://www.flashscore.com/team/manchester-united/ppjDR086/results/"
driver.get(url)

Team = 'Manchester Utd'
results = WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH,"//div[contains(@class,'event__participant home')][text()='" + Team + "']//following-sibling::span[1]")))
print(len(results))

试试这个xpath-

//div[contains(text(),'Manchester Utd')]/following-sibling::span

相关问题 更多 >