在动态变化的 html 中抓取隐藏元素

时间:2021-06-01 05:45:05

标签: python selenium beautifulsoup

我需要从动态变化的 html 中抓取一些信息。有问题的网站是: https://www.mitartlending.com/featuredartworks。在这里,当您单击给定的图像并将鼠标悬停在放大的图像上时,会弹出一个文本叠加层。我正在尝试抓取该文本。在尝试用 BS 做到这一点后,我决定我可能不得不使用硒。你会如何着手解决这个问题?到目前为止,我有:

from selenium import webdriver
driver = webdriver.Chrome('/Users/Abramo/SeleniumDrivers/chromedriver') 
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver.get('https://www.mitartlending.com/featuredartworks')

driver.implicitly_wait(3)

my_element = driver.find_element_by_xpath(f'/html/body/div[5]/div[2]/div/main/section/div/div/div/div[3]/div/div/div/div[1]/div/a/img')
my_element.click()                                        
   

copy_from = driver.find_element_by_class_name('sqs-lightbox-meta overlay-description-visible')
my_next_button = driver.find_element_by_class_name('sqs-lightbox-next')

2 个答案:

答案 0 :(得分:0)

您可以通过

找到这些图像中的任何一个
images = driver.find_elements_by_xpath('//img[contains(@class,'thumb-image loaded')]')

因此,例如点击您可以使用的第二张图片

images[1].click()

要将鼠标悬停在元素上,您可以这样做:

from selenium.webdriver.common.action_chains import ActionChains

hover = ActionChains(driver).move_to_element(images[1])
hover.perform()

现在,当文本出现时,您可以使用

来定位并获取它
text = driver.find_elements_by_xpath('(//img[contains(@class,'thumb-image loaded')])[2]/..//p').text

对于那里的任何其他图像也可以这样做。
总而言之,代码将如下所示:

from selenium.webdriver.common.action_chains import ActionChains

images = driver.find_elements_by_xpath('//img[contains(@class,"thumb-image loaded")]')
images[1].click()

time.sleep(2)
hover = ActionChains(driver).move_to_element(images[1])
hover.perform()

time.sleep(2)
text = driver.find_elements_by_xpath('(//img[contains(@class,"thumb-image loaded")])[2]/..//p')
for t in text:
    print(t.text)

我添加 sleeps 只是为了简化它,而更喜欢使用预期的条件等待

答案 1 :(得分:0)

数据都在属性中。你只需要提取适当的。不需要硒的开销。

import requests
from bs4 import BeautifulSoup as bs

r = requests.get('https://www.mitartlending.com/featuredartworks')
soup = bs(r.content, 'lxml')
results = {i['data-title']:' '.join(bs(i['data-description'], 'lxml').text.split('\n')) for i in soup.select('.margin-wrapper > a')}
print(results)