在Python中进行网页抓取 - 从网站中提取一个值

问题描述 投票:1回答:1

我想从这个网站提取两个值。

bizportal.co.il

其中一个值是右边的美元汇率,左边的是企业的百分比。

问题是......当我得到美元汇率值后,这个数字被四舍五入了(你可以在终端看到)......我想得到网站上显示的准确数字。

如果有人能分享一个Python中的网页抓取的友好文档,我会很高兴。最有用的功能和更多...

P.S: 有谁知道如何摆脱在VS中运行代码时弹出的python终端窗口?我只是希望输出将在VS中 - 在交互式窗口中... ...

希望有人能帮忙...

先谢谢你了。

my_url = "https://www.bizportal.co.il/forex/quote/generalview/22212222" 

uClient = urlopen(my_url) 

page_html = uClient.read()  

uClient.close()                                                                      

page_soup = BeautifulSoup(page_html, "html.parser")                                 

div_class = page_soup.findAll("div",{"class":"data-row"})                      

print (div_class)
#print(div_class[0].text)
#print(div_class[1].text)

dollar rate

python beautifulsoup urllib
1个回答
2
投票

数据是通过Ajax动态加载的,但你可以模拟这个请求与 requests 模块:

import json
import requests

url = 'https://www.bizportal.co.il/forex/quote/generalview/22212222'
ajax_url = "https://www.bizportal.co.il/forex/quote/AjaxRequests/DailyDeals_Ajax?paperId={paperId}&take=20&skip=0&page=1&pageSize=20"
paper_id = url.rsplit('/')[-1]
headers = {'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:76.0) Gecko/20100101 Firefox/76.0'}

data = requests.get(ajax_url.format(paperId=paper_id), headers=headers).json()

# uncomment this to print all data:
#print(json.dumps(data, indent=4))

# print first one
print(data['Data'][0]['rate'], data['Data'][0]['PrecentageRateChange'])

打印。

3.4823 -0.76%

0
投票

问题是这个元素是用Javascript动态更新的,你将无法用urllib或request搜刮 "update "值。你将无法用urllib或requests来刮取 "up to date "的值。当页面被加载时,它有一个最近的值被填充(很可能来自数据库),然后通过Javascript将其替换为实时数字。

在这种情况下,最好使用类似Selenium的东西来加载网页--这样可以让javascript在页面上执行,然后再刮取数字。

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time

options = Options()
options.add_argument("--headless") # allows you to scrape page without opening the browser window
driver = webdriver.Chrome('./chromedriver', options=options)

driver.get("https://www.bizportal.co.il/forex/quote/generalview/22212222")
time.sleep(1) # put in to allow JS time to load, sometimes works without.
values = driver.find_elements_by_class_name('num')
price = values[0].get_attribute("innerHTML")
change = values[1].find_element_by_css_selector("span").get_attribute("innerHTML")

print(price, "\n", change)

输出。

╰─$ python selenium_scrape.py
3.483 
 -0.74%

你应该熟悉Selenium,了解如何设置它,并运行它--这包括安装浏览器(在本例中我使用Chrome,但你也可以使用其他浏览器),了解从哪里获得浏览器驱动程序(本例中是Chromedriver),并了解如何解析页面。你可以在这里了解所有关于它的信息 https:/www.selenium.devdocumentationen

© www.soinside.com 2019 - 2024. All rights reserved.