【问题标题】:Retrieving content using Beautifulsoup and selectors使用 Beautifulsoup 和选择器检索内容
【发布时间】:2020-01-04 04:49:22
【问题描述】:

试图检索嵌入在 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”。而是看到“无” - “价格框: 无”

【问题讨论】:

    标签: python web-scraping beautifulsoup python-requests urllib


    【解决方案1】:

    很多内容都是动态的。您可以轻松地对这些信息进行正则表达式

    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

    【讨论】:

    • QHarr,我在正则表达式方面仍然落后,但我不会被困在这里很长时间。大声笑!
    • @sim 你看过我提供的那些 youtube 链接了吗?另外,我访问了this,但没有花时间正确地完成这一切。
    • 是的,链接中的内容是宝藏。会深入探讨。谢谢。
    • 问题:你怎么知道内容是动态的?抱歉,对这一切都很陌生。
    • 天哪,你的解决方案奏效了!!两个问题:1)为什么要在网址末尾添加“&guccounter=1”。我用我原来的网址试了一下,效果很好。第二个问题,什么是“#cal-res-table a'”?谢谢!!
    猜你喜欢
    • 1970-01-01
    • 2017-12-26
    • 1970-01-01
    • 1970-01-01
    • 2021-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多