1。第一个选项,您可以使用 BeautifulSoup 做什么
请注意,您要获取的元素位于 iframe 中,这意味着这是另一个请求,与您提出的请求不同,您可以编写代码来遍历所有 iframes 并在找到时打印价格iframe_soup.find("td",{"class":"RightBlack"})。
我建议使用 except 语句,因为这样做很容易陷入 url 陷阱:
from urllib.request import urlopen as ureq
from bs4 import BeautifulSoup as soup
my_url = 'http://www.calcalist.co.il/stocks/home/0,7340,L-4135-22212222,00.html?quote=%D7%93%D7%95%D7%9C%D7%A8'
uclient = ureq(my_url)
page_html = uclient.read()
page_soup = soup(page_html, "html.parser")
iframesList = page_soup.find_all('iframe')
i = 1
for iframe in iframesList:
print(i, ' out of ', len(iframesList), '...')
try:
uclient = ureq("http://www.calcalist.co.il"+iframe.attrs['src'])
iframe_soup = soup(uclient.read(), "html.parser")
price = iframe_soup.find("td",{"class":"RightBlack"})
if price:
print(price)
break
except:
print("something went wrong")
i+=1
运行代码,输出如下:
1 out of 8 ...
2 out of 8 ...
3 out of 8 ...
4 out of 8 ...
5 out of 8 ...
<td class="RightBlack">3.5630</td>
所以现在我们得到了我们想要的:
>>> price
<td class="RightBlack">3.5630</td>
>>> price.text
'3.5630'
这是一个建议,要进行请求和 JavaScript 处理,您应该使用带有 JS 解释器的 Selenium,下面我使用的是 ChromeDriver,但是您也可以使用 PhantomJS 进行无头浏览。检查框架元素,我们知道它的id是"StockQuoteIFrame",我们使用.switch_to_frame,然后我们很容易找到我们的price:
from selenium import webdriver
from bs4 import BeautifulSoup
url = 'http://www.calcalist.co.il/stocks/home/0,7340,L-4135-22212222,00.html?quote=%D7%93%D7%95%D7%9C%D7%A8'
browser = webdriver.Chrome()
browser.get(url)
browser.switch_to_frame(browser.find_element_by_id("StockQuoteIFrame"))
price = browser.find_element_by_class_name("RightBlack").text
输出当然和第一个选项一样:
>>> price
'3.5630'