簡體   English   中英

使用 Python + Selenium WebDriver 檢查網頁上是否存在文本

[英]Check if text exists on a webpage using Python + Selenium WebDriver

我正在嘗試使用 Selenium 查看網頁上是否存在某個字符串並相應地返回 true/false。 我似乎找不到其他人用它來返回 boolean。

我在下面包含了 function 的代碼,盡管我也嘗試了很多其他變體,包括 webdriverwait、正文搜索、通過 xpath 搜索元素、unittest 和 assert 等等。 任何建議將不勝感激!

from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
import pandas as pd
import time



# SET EVERYTHING UP FOR THE TASK
# open the spreadhseet and read in data
df = pd.read_csv('C:\\Users\\jdoe\\Downloads\\firms.csv')
# create new column for word search results
df ['WORD PRESENCE?'] = ""
# make sure pandas prints entire df
pd.set_option("display.max_rows", None, "display.max_columns", None)


# designate what you'd like to search for -- FILL IN THE WORD
wordsearch = "internet"
name_to_search = ""



# chrome driver path & location
driver = webdriver.Chrome(r"C:\\Users\\jdoe\\chromedriver.exe")

def setup():
    # reset the driver and open google
    driver.get("https://google.com")

def search(input_text):
    # access the search bar and send a command
    search = driver.find_element("name", "q")
    search.send_keys(input_text)
    search.send_keys(Keys.RETURN)

def opensite():
    # open the top search result
    website = driver.find_element(By.CLASS_NAME, "yuRUbf")
    website.find_element(By.XPATH, "./a").click()

def findtext(wordsearch):
    # find out if specific text is on the webpage and print result
    #return wordsearch in driver.page_source
    if wordsearch in driver.page_source:
        return True
    else:
        return False

def reset():
    # close the webdriver
    driver.quit()
    
    
    
# go through each column in the spreadsheet and fill everything in
for i, rows in df.iterrows():
    setup()
    
    # search for website and open it
    name_to_search = df.at[i, "NAME"]
    search(name_to_search)
    opensite()
    
    # fill in the website column of the spreadsheet
    current_website = driver.current_url
    df.at[i, "WEBSITE"] = current_website
    
    # find out of the designated word is on the webpage
    time.sleep(2)
    is_word_there = findtext(wordsearch)
    df.at[i, "WORD PRESENCE?"] = is_word_there
    
print(df)
reset()

我想到了。 正好和python區分大小寫有關,所以我又寫了一個function來適配全大寫,全小寫,首字母大寫。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM