我必須遵循我試圖抓取的網站上的 HTML:
<div class="test-section-container">
<div>
<span class="test-section-title">Section Title</span>
<div style="display: inline-block; padding: 0.05rem;"></div>
</div>
<div style="cursor: pointer; background-color: rgb(248, 248, 248); display: flex; line-height: 1.2; margin-bottom: 0.07rem;">
<div style="width: 0.5rem; flex-shrink: 0; background-color: rgb(245, 222, 136);"></div>
<div style="padding: 0.07rem; overflow: hidden;">
<div style="font-size: 0.18rem; text-overflow: ellipsis; overflow: hidden; white-space: nowrap;">Newsletter 1</div>
<div style="font-size: 0.13rem; color: rgb(102, 102, 102);">2021 11 8</div>
</div>
</div>
<div style="cursor: pointer; background-color: rgb(248, 248, 248); display: flex; line-height: 1.2; margin-bottom: 0.07rem;">
<div style="width: 0.5rem; flex-shrink: 0; background-color: rgb(221, 221, 221);"></div>
<div style="padding: 0.07rem; overflow: hidden;">
<div style="font-size: 0.18rem; text-overflow: ellipsis; overflow: hidden; white-space: nowrap;">Newsletter 2 </div>
<div style="font-size: 0.13rem; color: rgb(102, 102, 102);">2021 11 3</div>
</div>
</div>
這是我正在使用的 selenium/python 代碼:
driver.get("http://www.testwesbite.org/#/newsarticles")
results = driver.find_elements_by_class_name('test-section-container')
texts = []
for result in results:
text = result.text
texts.append(text)
print(text)
這給了我一個輸出:
Newsletter 1
2021 11 8
Newsletter 2
2021 11 3
如果我使用以下代碼:
first_result = results[0]
first_result.click()
它確實點擊了第一篇文章,但results[1]給了我一個越界錯誤。
我將如何點擊第二篇文章?
uj5u.com熱心網友回復:
由于您使用driver.find_elements_by_class_name('test-section-container')了以下所有文本:
- 時事通訊 1
- 2021 11 8
- 通訊2
- 2021 11 3
在results[0]元素內并且results[1]不存在。因此你面臨越界錯誤
解決方案
要單擊每個results[0],results[1]您可以使用:
driver.get("http://www.testwesbite.org/#/newsarticles")
results = driver.find_elements(By.CSS_SELECTOR, "div.test-section-container div[style*='nowrap']")
texts = []
for result in results:
text = result.text
texts.append(text)
print(text)
現在您可以單擊單個專案:
first_result = results[0]
first_result.click()
和
second_result = results[1]
second_result.click()
注意:您必須添加以下匯入:
from selenium.webdriver.common.by import By
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/360851.html
下一篇:列印沒有索引的串列的最新元素
