python 如何修复错误驱动程序.find_element(By.CLASS_NAME,name),并将结果保存在txt文件中?

ekqde3dh  于 2023-11-16  发布在  Python
关注(0)|答案(1)|浏览(90)

这是在virustotal的任何搜索结果的HTML。

<div class="positives"> <!--?lit$32274217$-->39 </div>

字符串
HTML image of the website and the needed data to be extracted

我的密码

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time

driver = webdriver.Chrome()
driver.get("https://www.virustotal.com/gui/home/search")
driver.maximize_window()

wait = WebDriverWait(driver, 15)
search_input = wait.until(EC.element_to_be_clickable((driver.execute_script("return document.querySelector('home-view').shadowRoot.querySelector('vt-ui-search-bar').shadowRoot.querySelector('input#searchInput')"))))
search_input.send_keys("759b1fcbdf4ad54bb8adc2c060df8ab5")
search_input.send_keys(Keys.RETURN)  # Press Enter
time.sleep(5)

# Get the result and write it to a file
result = driver.find_element(By.CLASS_NAME, 'div > div > div.positives')
result_text = str(result.text)
with open('output.txt', 'a') as f:
    f.write(result_text)
    f.write('\n' * 10)

driver.quit()

错误:

result = driver.find_element(By.CLASS_NAME, 'div > div > div.positives')
 in find_element
    return self.execute(Command.FIND_ELEMENT, {"using": by, "value": value})["value"]

kgsdhlau

kgsdhlau1#

错误的根本原因:

result = driver.find_element(By.CLASS_NAME, 'div > div > div.positives')

字符串
上面一行不对,应该是By.CSS_SELECTOR, 'div > div > div.positives'

**解决方案:**上面说了,就像在这个answer中一样,你需要处理shadow-root元素。

修改代码如下:

result = wait.until(EC.element_to_be_clickable((driver.execute_script("return document.querySelector('file-view').shadowRoot.querySelector('vt-ui-main-generic-report').shadowRoot.querySelector('vt-ui-detections-widget').shadowRoot.querySelector('div.positives')"))))
# result = driver.find_element(By.CLASS_NAME, 'div > div > div.positives')

更新:

result = wait.until(EC.element_to_be_clickable((driver.execute_script("return document.querySelector('file-view').shadowRoot.querySelector('vt-ui-main-generic-report').shadowRoot.querySelector('vt-ui-detections-widget').shadowRoot.querySelector('div.positives')"))))
# result = driver.find_element(By.CSS_SELECTOR, 'positives')
result_text = str(result.text)
print(result_text)
with open('output.txt', 'a') as f:
    f.write(result_text)
    f.write('\n' * 10)

driver.quit()


控制台结果:

39

Process finished with exit code 0

相关问题