<time class="_1o9PC Nzb55" datetime="2020-06-07T17:45:25.000Z" title="7. Juni 2020">Vor 1 Stunde</time>
我目前正在使用硒进行网络抓取。您所看到的代码是将图片发布到instagram时的html元素。我希望代码仅显示以下内容:
datetime="2020-06-07T17:45:25.000Z"
假设我按类找到了该元素,然后执行print(element.text)
。然后输出:“ Vor 1 Stunde”(抱歉,德语)。我不知道有没有办法做到这一点,但如果有,请告诉我。这是完整的代码:
from selenium import webdriver
import time, pyautogui, random
browser = webdriver.Firefox()
browser.get('https://www.instagram.com/')
time.sleep(1)
name = browser.find_element_by_xpath("/html/body/div[1]/section/main/article/div[2]/div[1]/div/form/div[2]/div/label/input")
name.click()
name.send_keys("username")
passwort = browser.find_element_by_xpath("/html/body/div[1]/section/main/article/div[2]/div[1]/div/form/div[3]/div/label/input")
passwort.send_keys("password")
browser.find_element_by_xpath("/html/body/div[1]/section/main/article/div[2]/div[1]/div/form/div[4]/button/div").click()
time.sleep(3)
browser.find_element_by_xpath("/html/body/div[1]/section/main/div/div/div/div/button").click()
time.sleep(2)
browser.find_element_by_xpath("/html/body/div[4]/div/div/div[3]/button[2]").click()
time.sleep(2)
suche = browser.find_element_by_class_name("LWmhU").click()
time.sleep(1)
pyautogui.typewrite("mmd")
pyautogui.typewrite(["enter"])
time.sleep(2.5)
acc = browser.find_element_by_xpath("/html/body/div[1]/section/nav/div[2]/div/div/div[2]/div[2]/div[2]/div/a[1]/div/div[2]/span").click()
print(acc)
time.sleep(1)
# click on the instagram picture
pyautogui.click(427, 754)
time.sleep(2)
uploaddate = browser.find_element_by_class_name("_1o9PC")
print(uploaddate.getAttribute("datetime"))
element.getAttribute("datetime")
对于HTML,datetime
是标记time
中的属性。因此,您可以使用.getAttribute()
来获取它。
所需的元素是启用了ReactJS的元素,因此要找到需要为WebDriverWait引入visibility_of_element_located()
的元素,可以使用以下Locator Strategies中的任何一个:
使用XPATH
:
print(WebDriverWait(browser, 20).until(EC.visibility_of_element_located((By.XPATH, "//time[text()='Vor 1 Stunde']"))).get_attribute("datetime"))
使用CSS_SELECTOR
:
print(WebDriverWait(browser, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "time[title$='Juni 2020'][datetime]"))).get_attribute("datetime"))
注:您必须添加以下导入:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC