我有问题
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome(
executable_path=r'C:\Users\Michelle\Downloads/chromedriver.exe')
#opens website%
driver.get("https://www.ebay.com")
#selects search bar and enters keys
inputElement = driver.find_element_by_id("gh-ac")
inputElement.send_keys('headphones')
inputElement.send_keys(Keys.ENTER)
Items = driver.find_elements_by_xpath('//*[@id="srp-river-results-
listing1"]/div/div[2]/a/h3')
Prices = driver.find_elements_by_xpath('//*[@id="srp-river-results-
listing1"]/div/div[2]/div[4]/div[1]/span')
print(Items[0].text + " : " + Prices[0].text)
driver.close()
好吧,我试图让ebay显示商品的名称和价格 但是在转到页面并查看价格的xpath之后,它们都是不同的
//*[@id="srp-river-results-listing1"]/div/div[2]/div[4]/div[1]/span
//*[@id="srp-river-results-listing2"]/div/div[2]
//*[@id="srp-river-results-listing3"]/div/div[2]/div[3]/div[1]/span
^ the xpaths
除了xpath之外,我还能如何让它们显示价格,有没有像使用元素那样的方式?
<span class="s-item__price">$99.00</span>
使用这样的元素^?
答案 0 :(得分:0)
我尝试了您的代码,但xpath表达式没有任何结果,请尝试使用更简单的CSS选择器表达式进行以下操作:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
def main():
driver = webdriver.Chrome(executable_path=r'C:\Users\Michelle\Downloads\chromedriver.exe')
driver.maximize_window()
try:
driver.get("https://www.ebay.com")
input_element = driver.find_element_by_id("gh-ac")
input_element.send_keys('headphones')
input_element.send_keys(Keys.ENTER)
items = driver.find_elements_by_css_selector('.srp-results .s-item .s-item__title')
prices = driver.find_elements_by_css_selector('.srp-results .s-item .s-item__price')
print("# Items: %d" % len(items))
print("# Prices: %d" % len(prices))
print(items[5].text + " : " + prices[5].text)
finally:
driver.quit()
if __name__ == '__main__':
main()
输出:
# Items: 60 # Prices: 60 2PCS New Headphones Earphones With Remote & Mic For Apple iPhone 6S 6 5 5S 4S : $28.97