简体   繁体   English

无法使用 Selenium 从网页获取文本

[英]Unable to get the text from a webpage using Selenium

I am simply trying to grab all of the text from the main page.我只是想从主页中获取所有文本。 This code returns nothing.此代码不返回任何内容。 The end-goal is to scan the page for when the shirt icon appears.最终目标是扫描页面以了解衬衫图标何时出现。 If it does click into the match.如果它确实点击进入比赛。 Thanks in advance:提前致谢:

First Picture attached is html of one match which I would like to loop through all of them on the page Second picture attached is html of shirt icon appearing附上的第一张图片是一个匹配的 html,我想在页面上循环播放所有这些第二张图片是出现的衬衫图标的 html

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
from selenium.webdriver.chrome.options import Options
from bs4 import BeautifulSoup
import time

PATH = "C:\Program Files (x86)\chromedriver.exe"
chrome_options = Options()
chrome_options.add_argument(" - incognito")
driver = webdriver.Chrome(PATH,options=chrome_options)
driver.get("https://www.flashscore.com/")
driver.implicitly_wait(5)

try:
    main = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.CLASS_NAME, "sportName soccer"))
    )
    print(main.text)
except:
    print("No Text Found")
    driver.quit()

To get all the text inside that element:要获取该元素内的所有文本:

main = driver.find_element_by_xpath("//div[contains(@class,'sportName soccer')]")
print(main.text)

To get only the events仅获取事件

listofevents = driver.find_elements_by_xpath("//div[contains(@class,'event__match event__match--oneLine event__match--scheduled')]")
for i in listofevents:
print(i.text)

Simply change your locator strategy from using class to xpath.只需将您的定位器策略从使用 class 更改为 xpath。

try:
    main = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.XPATH, '//div[@id="live-table"]/div[@class="event"]/div[@class="leagues--live "]/div[@class="sportName soccer"]')))
    print(main.text)
except:
    print("No Text Found")
driver.quit()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM