我正在尝试从应用商店https://apps.apple.com/us/app/mercer-marketplace-benefits/id1041417557
的xpath上方提取图像我使用xpath尝试了以下代码:
driver.get('https://apps.apple.com/us/app/mercer-marketplace-benefits/id1041417557')
rating_distr = WebDriverWait(driver,30).until(EC.presence_of_element_located((By.XPATH, """(//*[@id="ember290"]/div/div[2])""")))
print(rating_distr.get_attribute('innerHTML'))
但是输出的不是图像:
<figure class="we-star-bar-graph">
<div class="we-star-bar-graph__row">
<span class="we-star-bar-graph__stars we-star-bar-graph__stars--5"></span>
<div class="we-star-bar-graph__bar">
<div class="we-star-bar-graph__bar__foreground-bar" style="width: 76%;"></div>
</div>
</div>
<div class="we-star-bar-graph__row">
<span class="we-star-bar-graph__stars we-star-bar-graph__stars--4"></span>
<div class="we-star-bar-graph__bar">
<div class="we-star-bar-graph__bar__foreground-bar" style="width: 12%;"></div>
有什么方法可以将输出提取为图像?感谢您的帮助!
答案 0 :(得分:3)
正如我在评论中建议的那样,我认为更好/更快的方法是仅获取值而不是截屏。如果您截取屏幕截图,则必须手动打开它,然后以其他某种格式记录屏幕快照中的值,这将是一个漫长而乏味的过程。取而代之的是,只需从页面中抓取数据并以最终所需的格式转储它们即可。
例如,如果您仅查看5星级评分栏的HTML
<div class="we-star-bar-graph__row">
<span class="we-star-bar-graph__stars we-star-bar-graph__stars--5"></span>
<div class="we-star-bar-graph__bar">
<div class="we-star-bar-graph__bar__foreground-bar" style="width: 76%;"></div>
</div>
</div>
您会看到应用了一个类别we-star-bar-graph__stars--5
,该类别指示其星级。您还可以看到条形图的宽度已设置为style="width: 76%;"
,因此可以知道5星评级的百分比。有了这些信息,我们就可以抓取每颗星的评级。
ratings = driver.find_elements_by_css_selector("figure.we-star-bar-graph div.we-star-bar-graph__bar__foreground-bar")
# get the width of the entire bar
width = float(driver.find_elements_by_css_selector(".we-star-bar-graph__bar").value_of_css_property("width"))[:-2])
for i in range(len(ratings), 0, -1) :
# get the width of the rating
rating = float(ratings[len(ratings) - i].value_of_css_property("width")[:-2])
print(str(i) + "-star rating: " + str(rating / width * 100) + "%")
这应该转储类似
的值5-star rating: 76%
4-star rating: 12%
3-star rating: 4%
2-star rating: 1%
1-star rating: 6%
那可能不是您最终想要的格式,但是它应该使您指向正确的方向。
答案 1 :(得分:1)
打开网页并按ID滚动到元素,当我检查ID时,您要在网页中找到的部分为“ ember290”。
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
import pyscreenshot as ImageGrab
browser = webdriver.Chrome() # we are using chrome as our webbrowser
browser.get('https://apps.apple.com/us/app/mercer-marketplace-benefits/id1041417557')
#rating_distr = WebDriverWait(browser,30).until(EC.presence_of_element_located((By.XPATH, """(//*[@id="ember290"]/div/div[2])""")))
ActionChains(browser).move_to_element(browser.find_element_by_id('ember290')).perform()
im=ImageGrab.grab()
im.show()
im=ImageGrab.grab(bbox=(162,650,500,500))
im.show()
ImageGrab.grab_to_file('im.png')
滚动完成后,请截屏。