python - 漂亮的汤刮取一个不是首先出现的变量
问题描述
根据Python - ETF 每日数据网络抓取,我尝试抓取费用比率。
import requests
from bs4 import BeautifulSoup
html = requests.get("https://www.marketwatch.com/investing/fund/ivv").text
soup = BeautifulSoup(html, "html.parser")
if soup.h1.string == "Pardon Our Interruption...":
print("They detected we are a bot. We hit a captcha.")
else:
price = soup.find("li", class_="kv__item").find("span").string
print(price)
但是,这会返回open
. 我怎么能告诉它在返回时取第 10 个li
而不是第一个?
解决方案
使用最新的 bs4,您绝对可以使用 css nth-of-type选择器
import requests
from bs4 import BeautifulSoup
html = requests.get("https://www.marketwatch.com/investing/fund/ivv").text
soup = BeautifulSoup(html, "lxml")
if soup.h1.string == "Pardon Our Interruption...":
print("They detected we are a bot. We hit a captcha.")
else:
price = soup.select_one('.list--kv li:nth-of-type(10) span').string
print(price)
您甚至可以将选择器缩短为:
li:nth-of-type(10) span
对于 li 内的 span 列表:
.list--kv li span
推荐阅读
- visual-studio-code - VSCode 在 OS 更新后以黑底灰显示代码
- pyspark - 如何将字符串附加到pyspark中列出的数据框列
- python - 无法加载请求的 DLL 找不到指定的模块
- assembly - 反向字符串 MASM
- c++ - 如何在 C++ 中将空格分隔的输入插入数组
- linux - 如果我将浮点数除以零,为什么会引发“浮点异常”?
- python - 如何在matplotlib中向相反方向(向下)添加第三个y轴?
- python - 语音字符到语音
- file - URLDownloadToFile 中的 IBindStatusCallback 未正确返回最终文件大小
- php - 将所有购买重定向到自定义感谢页面 - 特定页面 ID 除外