如何访问python中具有相同类名的第二个元素



我在一个网页上有两个元素的类同名,我使用selenium,我必须调用第二个元素,但我不能。我该怎么办?我试过使用你读到的代码的firts类,但它给了我错误:

Message: element click intercepted: Element <a class="navigate-target navigate-next"

第一个代码:

<a class="navigate-target navigate-prev no-outline" href="..." title="..." data-track="prevPhotoButtonClick" data-action="ad" style="height: 430px;">
<span class="hide-text">←</span>
</a>

第二个代码(我需要的(:

<a class="navigate-target navigate-next no-outline" href="..." title="..." data-track="nextPhotoButtonClick" data-action="ad" style="height: 430px;">
<span class="hide-text">→</span>
</a>

这是我的代码,它并不完美,但可以用

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import requests, time, os, bs4
os.chdir('/home/vices/Documents/Python/document_test/cats')
os.makedirs('/home/vices/Documents/Python/document_test/cats/Foto_salvate', exist_ok=True)
def download():
chrome_options = Options()
chrome_options.add_argument("incognito")
chrome_options.add_experimental_option("detach", True)
driver = webdriver.Chrome('/home/vices/Documents/Python/Driver/chromedriver', chrome_options=chrome_options)
driver.get('https://flickr.com/')
driver.find_element_by_id('search-field').click()
driver.find_element_by_id('search-field').send_keys('husqvarna')
driver.find_element_by_class_name('search-icon-button').click()
time.sleep(2)
driver.find_elements_by_class_name('photo-list-photo-interaction')[1].click()
time.sleep(2)

while True:
url = driver.current_url
print("Downloading page...")
res = requests.get(url)
res.raise_for_status()
soup = bs4.BeautifulSoup(res.text, features="lxml")
foto = soup.select('img')
foto_url = 'https:' + foto[1].get('src')
print("Downloading foto")
res = requests.get(foto_url)
res.raise_for_status()
imagefile = open(os.path.join('Foto_salvate', os.path.basename(foto_url)), 'wb')
for chunk in res.iter_content(100000):
imagefile.write(chunk)
imagefile.close()
driver.find_elements_by_class_name('hide-text')[1].click()


download()

您应该使用:find_elements_by_class_name如本文所述:

https://selenium-python.readthedocs.io/api.html#selenium.webdriver.remote.webdriver.WebDriver.find_elements_by_class_name

然后在输出中获取列表的第二个元素。

最新更新