如何使用R语言为本地电视门户网站指定评论点赞?
Great question! Let's break this down step by step—since rvest is perfect for scraping static content, but clicking that green like arrow triggers a dynamic backend request (not just a static page update), we'll need two practical approaches to get this done: either reverse-engineer the site's like API, or simulate a real browser click with automation.
Approach 1: Reverse-Engineer the Like API (More Efficient)
This method mimics the backend request your browser sends when you click "like", using httr to replicate it directly in R.
Step 1: Locate the Target Comment from User "eto"
First, use rvest to find the comment and extract its unique ID (the site needs this to know which comment to like):
library(rvest) library(stringr) url1 <- "http://rs.n1info.com/Comment/StandardComment/637905/Sci-Tech/Facebook-ce-dati-prednost-verodostojnim-medijskim-kucama.html" webpage <- read_html(url1, encoding = "UTF-8") # Grab all comment blocks (adjust the CSS selector if the site uses a different class) comments <- html_nodes(webpage, ".comment-item") # Loop through comments to find the one by "eto" target_comment <- NULL for (comment in comments) { # Extract the username (tweak the selector to match the site's username element) username <- html_text(html_node(comment, ".comment-author-name")) %>% str_trim() if (username == "eto") { target_comment <- comment break } } # Extract the comment's unique ID (check the comment block's attributes—look for data-id, data-comment-id, etc.) if (!is.null(target_comment)) { comment_id <- html_attr(target_comment, "data-id") cat("Found target comment ID:", comment_id, "\n") } else { stop("Couldn't locate a comment from user 'eto'") }
Step 2: Capture the Like Request with Browser Dev Tools
- Open the comment page in Chrome/Firefox
- Right-click the green like arrow → Inspect to open Dev Tools
- Switch to the Network tab, then click the like arrow
- Look for an XHR/fetch request (usually named something like
VoteUporLikeComment) - Note these details:
- The request URL (e.g.,
http://rs.n1info.com/Comment/VoteUp) - Request method (POST/GET)
- Required parameters (e.g.,
commentId=637905or a CSRF token) - Any cookies or headers sent with the request
- The request URL (e.g.,
Step 3: Replicate the Request in R with httr
Use a session to maintain cookies (some sites require active session cookies to allow likes):
library(httr) # Start a session to persist cookies from the initial page load session <- session(url1) # Build the request using the details from Dev Tools vote_api_url <- "http://rs.n1info.com/Comment/VoteUp" # Replace with your actual API URL request_body <- list( commentId = comment_id, # Add any other required parameters (e.g., csrfToken = "xxx") ) # Send the POST request (use GET if the site uses that method instead) response <- session_post( session, vote_api_url, body = request_body, encode = "form" # Use "json" if the site sends JSON data instead of form data ) # Check if the like was successful if (http_status(response)$category == "Success") { cat("Successfully liked the comment from 'eto'!\n") } else { cat("Like failed. Response message:", content(response, "text"), "\n") }
Approach 2: Simulate Browser Clicks with RSelenium (Beginner-Friendly)
If reverse-engineering the API feels overwhelming, RSelenium lets you control a real browser to mimic your manual click—no need to dig into backend requests.
Step 1: Set Up RSelenium
First, install the package and start a browser session (we'll use Chrome here):
install.packages("RSelenium") library(RSelenium) # Start a Chrome browser session (adjust the port if needed) driver <- rsDriver(browser = "chrome", port = 4567L) remDr <- driver[["client"]]
Step 2: Navigate to the Page and Click the Like Button
# Open the comment page in the browser remDr$navigate(url1) # Find all username elements and locate the one for "eto" username_elements <- remDr$findElements(using = "css selector", value = ".comment-author-name") for (elem in username_elements) { if (elem$getElementText()[[1]] == "eto") { # Find the parent comment block, then the green like icon parent_comment <- elem$findElement(using = "xpath", value = "./ancestor::div[contains(@class, 'comment-item')]") like_button <- parent_comment$findElement(using = "css selector", value = ".comment-likes-icon") # Click the like button like_button$clickElement() cat("Clicked the like button for 'eto'!\n") break } } # Clean up: close the browser and stop the driver remDr$close() driver$server$stop()
Important Tips
- Anti-Scraping Checks: Many sites block automated requests. If you hit errors, check if you need to log in first (RSelenium makes this easy—just enter your credentials manually in the browser window).
- Selector Updates: CSS/XPath selectors (like
.comment-itemor.comment-author-name) depend on the site's HTML structure. Use your browser's Inspect tool to verify them if they stop working. - Rate Limiting: Don't send too many requests too quickly—you might get temporarily blocked from the site.
内容的提问来源于stack exchange,提问作者Newbie_R

