C# + Selenium:如何根据元素文本定位目标区块并提取计时器数据
Hey there! Let's tackle your questions step by step.
Here are some focused areas to explore next:
筛选含关键词的区块
Once you've grabbed all thesport--blockelements, loop through each one and check if its text content includes "Футбол". In C# Selenium, you can use theTextproperty of theIWebElementfor this. Just note that for dynamic pages, you'll want to use explicit waits (viaWebDriverWait) to ensure eachlielement is fully loaded before checking its text—this avoids race conditions where elements aren't rendered yet.处理动态计时器
First, identify the timer's unique selector within the targetsport--block(like a specific class name, e.g.,dynamic-timer). Since the value updates dynamically, you'll need to periodically fetch the element's text (orinnerTextattribute, if theTextproperty doesn't reflect real-time changes) instead of grabbing it once. You can set up a loop with a short delay (usingThread.Sleepor a conditional wait) to capture the current value at intervals.规避固定XPath的局限性
Instead of relying on brittle fixed XPaths, use relative selectors tied to the filteredsport--block. For example, once you have the matchinglielement, useelement.FindElement(By.CssSelector(".your-timer-class"))to locate the timer within it—this keeps your code resilient to changes in the overall page structure.
Absolutely! Here's why:
- Selenium is built explicitly for interacting with dynamic web pages, handling AJAX loads, and rendering JavaScript content—perfect for your use case where fixed XPaths won't work.
- The C# binding for Selenium is well-maintained, with robust support for waits, element querying, and browser automation.
- You can leverage C#'s strong typing and built-in file I/O libraries to easily write the extracted timer values to a file once you've captured them.
内容的提问来源于stack exchange,提问作者The Vee

