如何在driver.get()中为link_of_item添加单引号?
Correcting Your Newegg Scraper Code
Hey there! Let's break down what you need to do here, and fix a couple of common issues in your code along the way.
First, let's clarify the driver.get() line confusion:
- If you write
driver.get('link_of_item'), you're passing the literal string"link_of_item"instead of the actual URL the user entered. That's not what you want—your original linedriver.get(link_of_item)is actually correct, becauselink_of_itemstores the input URL as a string.
However, I noticed your XPath expressions use HTML entities (") instead of actual quotes, which will cause errors in Python. Let's fix those and clean up the code for better readability:
Here's the revised, working code:
from selenium import webdriver # Don't forget this import! # Get the item link from user input link_of_item = input('Please paste here the link of item from newegg:\n') # Initialize your browser driver (example uses Chrome; adjust for your browser) driver = webdriver.Chrome() # Load the item page (this line is correct as-is—no quotes needed around the variable) driver.get(link_of_item) # Fetch and print the item name (fixed XPath with regular quotes) item_name = driver.find_element_by_xpath('//*[@id="app"]/div[2]/div[1]/div/div/div[2]/div[1]/div[5]/h1').text print('Name of item:', item_name) # Fetch and print the current price (fixed XPath with regular quotes) current_price = driver.find_element_by_xpath('//*[@id="app"]/div[2]/div[1]/div/div/div[1]/div[1]/div[1]/div[3]/div[1]/div[2]/strong').text print('Price of item now is:', current_price) # Get the desired price from the user desired_price = input("Write the price you want to get: ")
Key Fixes & Explanations:
- Replaced HTML entities in XPaths: Swapped
"with regular double quotes ("). Python uses actual string literals, not HTML entity codes. - No quotes around
link_of_item: The variable already holds the URL string from user input—passing it directly givesdriver.get()the correct value, not the variable name itself. - Added readable variable assignments: Storing element text in variables like
item_namemakes the code easier to debug and maintain. - Included required imports: You need to import Selenium's
webdrivermodule for the code to run without errors.
内容的提问来源于stack exchange,提问作者chen sliktar
相关产品推荐
相关产品推荐

