python - 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)
但结果是:[]
因为那里什么都没有。
如何解决这个...?
解决方案
可能更容易使用正则表达式来查找该类值。然后搜索特定文本并获取下一个兄弟元素。
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>]
推荐阅读
- c - 如何在我的代码逻辑中找到错误?
- c# - 从远程启动的进程访问 Remote PC 注册表
- r - R dplyr::summarize groups by user defined functions
- dialogflow-es - 有什么方法可以从对话框流中获取“类型”的文本
- java - 我想在处理中使用 keyPressed() 稍微移动一个椭圆,但是当我这样做时,它会添加另一个椭圆而不是去掉一个
- ruby-on-rails - 如何为模型设置随机数 before_save?
- node.js - Mongoose:更新数组中的对象(批量写入)
- regex - 正则表达式(记事本++)插入,而不是替换
- asp.net - 登录 Blazor 服务器应用程序时如何显示加载图标?
- php - PHP 没有得到改造发送的 JSON 值