首页 > 解决方案 > BeautifulSoup 返回 None 即使那里有东西

问题描述

在此处输入图像描述

我正在尝试提取有关 Investing.com 中“流通股”的信息

当我使用鼠标右键单击“复制选择器”时,它给出:

    #leftColumn > div.clear.overviewDataTable.overviewDataTableWithTooltip > div:nth-child(14) > span.float_lang_base_2.bold

通过使用它,我尝试了 BeautifulSoup 代码:

    from bs4 import BeautifulSoup
    import urllib.request as req


    res = req.Request("https://www.investing.com/equities/apple-computer-inc", headers={'User-Agent': 'Mozilla/5.0'})
    response = req.urlopen(res).read()

    soup = BeautifulSoup(response, "html.parser")

    num_shares = soup.select("#leftColumn > div.clear.overviewDataTable.overviewDataTableWithTooltip > div:nth-child(14) > span.float_lang_base_2.bold")
    print(num_shares)

但结果是:[]因为那里什么都没有。

如何解决这个...?

标签: pythonpython-3.xbeautifulsoup

解决方案


可能更容易使用正则表达式来查找该类值。然后搜索特定文本并获取下一个兄弟元素。

import requests
from bs4 import BeautifulSoup
import re

url = 'https://www.investing.com/equities/apple-computer-inc'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36'}

response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, 'html.parser')

overviewTbl = soup.find('div', {'class': re.compile(r"overviewDataTable")})
value = overviewTbl.find(text='Shares Outstanding').parent.next_sibling.text

输出:

print (value)
4,334,335,000

使用.select

但是要使用选择器,我认为使用nth-of-type可以代替nth-child. 或者至少它对我有用。

num_shares = soup.select("div.clear.overviewDataTable.overviewDataTableWithTooltip > div:nth-of-type(14) > span.float_lang_base_2.bold")
print(num_shares)

输出:

[<span class="float_lang_base_2 bold">4,334,335,000</span>]

推荐阅读