python - 使用 Beautifulsoup 和选择器检索内容
问题描述
试图检索嵌入在 html 中的内容(文本)。没有得到内容。
尝试使用格式中的选择器来查找 price_box:
price_box = soup2.find('div', attrs={'title class': 'Fw(600)'})
# Import libraries
import requests
import urllib.request
import time
from bs4 import BeautifulSoup
# Set the URL you want to webscrape from
url = 'https://finance.yahoo.com/quote/NVDA?p=NVDA'
# Connect to the URL
response = requests.get(url)
# Parse HTML and save to BeautifulSoup object¶
soup = BeautifulSoup(response.text, "html.parser")
beta = soup.find('h1')
#print (beta)
link = beta.contents
variable = 'NVDA - NVIDIA Corporation'
test = 'NVDA - NVIDIA Corporation'
#<..>
url2 = 'https://finance.yahoo.com/calendar/earnings?from=2019-09-01&to=2019-09-07&day=2019-09-01'
response2 = requests.get(url2)
soup2 = BeautifulSoup(response2.text, "html.parser")
# alpha = soup2.find('')
# div = soup.find('a', {class_ ='D(ib) '})
# text = div.string
price_box = soup2.find('div', attrs={'title class': 'Fw(600)'})
#price = price_box.text
print("Price Box: "+ str(price_box)) # THIS IS WHAT I WANT
希望能看到“Senea”。而是看到“无” - “价格框:无”
解决方案
很多内容都是动态的。您可以轻松地对这些信息进行正则表达式
import requests, re
p = re.compile(r'"YFINANCE:(.*?)"')
r = requests.get('https://finance.yahoo.com/calendar/earnings?from=2019-09-01&to=2019-09-07&day=2019-09-01&guccounter=1')
print(p.findall(r.text)[0])
另一种方法是完全避免动态外观类
import requests
from bs4 import BeautifulSoup as bs
r = requests.get('https://finance.yahoo.com/calendar/earnings?from=2019-09-01&to=2019-09-07&day=2019-09-01&guccounter=1')
soup = bs(r.content, 'lxml')
print(soup.select_one('#cal-res-table a').text)
阅读:
推荐阅读
- oracle - 如何在 Oracle SQL developer(版本 20.4.1.407)中调试触发器?
- excel - 在 Excel 2010 中按升序或降序对数字的数字进行排序?
- mysql - MySQL:根据匹配的 id 将数据从一个表复制到另一个表时出现问题
- r - 将顶点属性数据添加到二分网络数据 - 用于 ERGM
- amazon-web-services - 负载均衡器方法(L4、L7)和 AWS
- vagrant - 安装 atom 时出现 Vagrant 错误
- python - 如何为随机森林的超参数调优定义标签和特征?
- laravel - Laravel - 如何添加 ALL 以选择下拉菜单并允许按全部过滤
- svg - 如何更改已设置的 SVG 属性
- git - 可以说是远程存储库?