【问题标题】:Unable to get the text from a webpage using Selenium无法使用 Selenium 从网页获取文本
【发布时间】:2021-02-17 13:17:23
【问题描述】:

我只是想从主页中获取所有文本。此代码不返回任何内容。最终目标是扫描页面以了解衬衫图标何时出现。如果它确实点击进入比赛。提前致谢:

First Picture 附件是一个匹配的 html,我想在页面上循环遍历所有匹配 Second picture附件是出现的衬衫图标的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()

【问题讨论】:

    标签: python selenium web-scraping beautifulsoup python-requests-html


    【解决方案1】:

    要获取该元素内的所有文本:

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

    只获取事件

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

    【讨论】:

    • 这很好用,谢谢。如果然后我想从每个元素继续并获取每个匹配项的 id 并且当出现衬衫图标时,我目前使用此代码时遇到错误` listofevents = driver.find_elements_by_xpath("//div[contains( @class,'event__match event__match--oneLine event__match--scheduled')]") for match in listofevents: n+=1 matchid = match.id try: lineuppresent = match.find_element_by_xpath('//*[@id='+matchid+ ']/svg[2]') lineuppresent.click() except: if n>5: break driver.quit()
    【解决方案2】:

    只需将定位器策略从使用类更改为 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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-04-30
      • 2012-10-07
      • 2021-09-23
      • 1970-01-01
      • 2011-12-18
      • 1970-01-01
      相关资源
      最近更新 更多