python - 使用 Beautifulsoup 和选择器检索内容

标签 python web-scraping beautifulsoup python-requests urllib

尝试检索嵌入在 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)

阅读:

  1. css selectors

关于python - 使用 Beautifulsoup 和选择器检索内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57735089/

相关文章:

python - Python 中的轮廓标签

python - 如何使用 python 在文件中找到连续数字的路径?

javascript - 使用 R 将字段添加到在线表单并抓取生成的 javascript 创建的表

python - 如何使用 Beautiful Soup BS4 抓取雅虎财经上的多个页面

python - 如何避免属性错误: 'NoneType' object has no attribute 'text' webscraping subreddits?

html - 如何使用python从html文件中抓取数据

python - 显示字典中的 seaborn 图

python - 替换重复键时选择要替换字典中的哪个值?

python - 在scrapy中提取json响应

python - 如何在抓取网页时单击下一步按钮