python - 如何使用 Selenium 和 Python 3 查找 iframe

标签 python selenium iframe automation

我在查找 this 上的一些数据时遇到问题页。我需要主图像和子图像的链接。我还需要“Ingridients et allergens”和“Mode d'empoli etservation”这两个选项卡下的文本。在我看来,这些是 iframe(或相同的 iframe),但无论我尝试什么都会返回错误。我们将非常感谢您的帮助。

提前致谢

编辑: 以下是无效代码的示例:

browser = webdriver.Firefox()
link = 'https://naturalia.fr/sardines-naturel-95g'
browser.get(link)

try:
    browser.find_element_by_xpath('''//*[@id="tab-label-ingredients_info-title"]''').click()
    descr = browser.find_element_by_class_name('cms-content')
    print('Description2: {}'.format(descr.text))
except Exception as e:
    print(e)

try:
    main_img = browser.find_element_by_xpath('''//*[@id="maincontent"]/div[2]/div[2]/div[2]/div/div[2]/div[2]/div[1]/div[3]/div[1]/img''').get_attribute('src')
    print(main_img)
except Exception as e:
    print(e)

最佳答案

您可以使用 img 标记的 xpath 找到图像 URL,然后访问它的 src 属性:

>>> driver.find_element_by_xpath('''//*[@id="maincontent"]/div[2]/div[2]/div[2]/div/div[2]/div[2]/div[1]/div[3]/div[1]/img''').get_attribute('src')
'https://naturalia.fr/media/catalog/product/cache/image/368x414/e9c3970ab036de70892d86c6d221abfe/3/2/3263670138016.1-0001.jpg'

对于选项卡下的文本,首先单击它们,然后继续提取文本,找到类“cms-content”:

>>> driver.find_element_by_xpath('''//*[@id="tab-label-ingredients_info-title"]''').click()
>>> mytext = driver.find_element_by_class_name("cms-content").text
>>> print(mytext)

Sardines, eau, citron* (pulpe, zeste et jus), sel de mer, thym*, fenouil*, persil*, laurier*.
*3.5% des ingrédients d'origine agricole sont issus de l’agriculture biologique certifié par FR BIO 10
Valeurs nutritionnelles moyennes Pour 100g
Energie 136 Kcal / 572 KJ
Matières grasses 4,9 g
Dont acides gras
(......)

您还可以使用来提取所有图像链接:

images = driver.find_elements_by_class_name("fotorama__img")
links = [image.get_attribute('src') for image in images]

>>> links
['https://naturalia.fr/media/catalog/product/cache/image/368x414/e9c3970ab036de70892d86c6d221abfe/3/2/3263670138016.1-0001.jpg', 'https://naturalia.fr/media/catalog/product/cache/image/368x414/e9c3970ab036de70892d86c6d221abfe/3/2/3263670138016.8-0001.jpg', 'https://naturalia.fr/media/catalog/product/cache/thumbnail/84x84/beff4985b56e3afdbeabfc89641a4582/3/2/3263670138016.8-0001.jpg', 'https://naturalia.fr/media/catalog/product/cache/thumbnail/84x84/beff4985b56e3afdbeabfc89641a4582/3/2/3263670138016.1-0001.jpg']

关于python - 如何使用 Selenium 和 Python 3 查找 iframe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45653215/

相关文章:

python ( Selenium ): how to login to a website with a login redirect/organization sign on

python - 尝试在 Python 3 中使用 selenium 获取文本

javascript - iframe 上的跨源

python - 比较运算符链接的结果

python - super() 在 Sublime Text 中抛出错误,在 PyCharm/Terminal 中有效

python - 如何在 Python 中让一个 Action 每分钟发生一次

Python 使用 Selenium 切换窗口

python - 如何在Python中为str子代覆盖ord行为?

jquery - iframe 不会以移动设备为中心?

html - CSS:通过 iframe 上的父级 div 插入阴影