我试图得到某一种产品的价格变动,但我得到的结果要么硒或美丽汤。
from selenium import webdriver
from bs4 import BeautifulSoup
import re
driver = webdriver.Chrome(executable_path='chromedriver.exe')
driver.get('https://www[.]cdkeys.com[/]playstation-network-psn[/]playstation-plus[/]1-year-playstation-plus-membership-ps3-ps4-ps-vita-digital-code')
search = driver.find_element_by_xpath('.//span[@class="price"]')
soup = BeautifulSoup(driver.page_source,'html.parser')
price = soup.find_all('span',{'class':['price']})search返回某种类型的对象,但带有空文本属性。
price得到了几十个结果,包括我感兴趣的结果。我相信它在某种API的背后,但我无法使用按XHR排序的Dev工具找到它。
发布于 2021-07-09 20:48:44
首先,你不需要把漂亮的汤和硒结合在一起
在这种情况下,他们中的一人足以完成全部工作。
我会选择beautifulSoup (带有请求)
原因是--这种抓取不需要javascript,而beautifulSoup的性能要比selenium轻得多。
关于刮擦法-
您得到了几十个结果,因为您只通过他的类名搜索元素,而这个名称中有很多元素。
其中一个解决方案是将多个
属性来找到正确的元素,正如我在下面的代码中所做的那样。
from bs4 import BeautifulSoup as BS
import requests
url = "https://www.cdkeys.com/playstation-network-psn/playstation-plus/1-year-playstation-plus-membership-ps3-ps4-ps-vita-digital-code?mw_aref=xcalibur"
r = requests.get(url)
soup = BS(r.text, features='html.parser')
product_main = soup.find('div', {'class': 'product-info-main'})
product_price = product_main.find('span', {'data-price-type': 'finalPrice', 'class': 'price-wrapper'})
print(product_price.text)发布于 2021-07-09 07:39:18
在获得带Selenium的元素以让元素完全加载之前,您应该添加一个等待。
from selenium import webdriver
from bs4 import BeautifulSoup
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import re
driver = webdriver.Chrome(executable_path='chromedriver.exe')
wait = WebDriverWait(driver, 20)
driver.get('https://www[.]cdkeys.com[/]playstation-network-psn[/]playstation-plus[/]1-year-playstation-plus-membership-ps3-ps4-ps-vita-digital-code')
search = wait.until(EC.presence_of_element_located((By.XPATH, './/span[@class="price"]')))
time.sleep(0.5)
prices_in_usd = driver.find_elements_by_xpath("//span[@class='price' and contains(text(),'$')]")
soup = BeautifulSoup(driver.page_source,'html.parser')
price = soup.find_all('span',{'class':['price']})如果您想获得元素文本,请不要忘记提取该文本
search_text = search.texthttps://stackoverflow.com/questions/68312939
复制相似问题