在StackOverflow遇Java Selenium相关问题,用WATIR读网页手机号失败求助
Hey Rajagopalan, I get it—trying to pull that phone number when it's hidden behind icon spans can be super frustrating. Let's break down how to fix this.
The issue here is that the phone number isn't stored as actual text in the HTML. Instead, each digit is represented by a <span> with a unique icon-* class, which uses CSS to display the digit as an image or icon font. So grabbing text directly won't work—we need to map each icon class to its corresponding digit.
Here's how to do it step by step:
Locate the container holding all the digit icons
First, target the parent element that wraps all those.mobilesvspans. Based on your HTML snippet, that's the<a>tag with classestel mtel, or you can go up to the outer<span class="telnowpr">if needed.Create a mapping of icon classes to digits
You'll need to check the website's CSS to see what digit eachicon-*class corresponds to. For example, inspecticon-bain your browser's dev tools—look at itsbackground-imageorcontentproperty to find out which digit it shows. Then build a hash to map these classes to their digits.Loop through each icon span and build the phone number
Iterate over every.mobilesvspan, pull its icon class, look up the digit from your mapping, and concatenate them all together.
Example Code
# Navigate to your target page first browser.goto("your_target_url_here") # Locate the container with the phone number icons phone_icon_container = browser.a(class: ["tel", "mtel"]) # Build your icon-to-digit mapping (update this based on the site's actual CSS!) icon_digit_map = { "icon-ba" => "1", "icon-ts" => "2", "icon-oqp" => "3", "icon-wx" => "4", "icon-nlm" => "5" # Add all other icon classes and their corresponding digits here } # Extract and assemble the phone number phone_number = phone_icon_container.spans(class: "mobilesv").map do |span| # Find the icon-specific class in the span's class list icon_class = span.classes.find { |cls| cls.start_with?("icon-") } # Use the mapping to get the digit, or an empty string if not found icon_digit_map[icon_class] || "" end.join # Output the result puts "Extracted Phone Number: #{phone_number}"
Quick Tips
- If the container locator doesn't work, adjust it to
browser.span(class: "telnowpr").a(class: ["tel", "mtel"])to target the outer span first. - Double-check the CSS for each icon class—sometimes sites use icon fonts where the
contentproperty holds the digit, or background images named with the digit (likedigit-1.png). - If some digits are missing from your mapping, the code will just skip them, so make sure you cover all icon classes used in the phone number.
内容的提问来源于stack exchange,提问作者Rajagopalan

