每次我运行代码都会得到不同的输出。
是的。每次页面返回不同的结果。即使您的选择是错误的,也不能解释您每次打印的结果都不同。我运行了几次,每次都得到不同的结果。
from bs4 import BeautifulSoup
import requests
import pandas as pd
r = requests.get("https://taripebi.ge/%E1%83%91%E1%83%94%E1%83%9C%E1%83%96%E1%83%98%E1%83%9C%E1%83%98%E1%83%A1-%E1%83%A4%E1%83%90%E1%83%A1%E1%83%94%E1%83%91%E1%83%98")
df=pd.read_html(r.text)
print(df)
输出
第一轮
[ 0 1 2 3 4 5 6 7
0 NaN ---00 2.4992 2.5700 2.64 2.63 2.59100 ---00
1 NaN ---00 2.3593 2.4800 2.58 ---00 2.53 ---00
2 NaN ---00 2.0493 2.2495 ---00 2.0500 2.2400 ---00
3 NaN ---00 2.4300 2.5300 2.63 2.4510 2.58 ---00
4 NaN 2.3593 2.4100 2.4900 2.6300 2.4910 2.59 ---00
5 NaN ---00 2.1593 2.4295 ---00 2.2010 2.4500 ---00
6 NaN 2.0400 2.1493 2.2495 ---00 2.05 ---00 2.24]
第 2 次运行
[ 0 1 2 3 4 5 6 7
0 NaN ---00 2.3593 2.4800 2.58 ---00 2.53 ---00
1 NaN ---00 2.4300 2.5300 2.63 2.4510 2.58 ---00
2 NaN ---00 2.1593 2.4295 ---00 2.2010 2.4500 ---00
3 NaN 2.3593 2.4100 2.4900 2.6300 2.4910 2.59 ---00
4 NaN 2.0400 2.1493 2.2495 ---00 2.05 ---00 2.24
5 NaN ---00 2.4992 2.5700 2.64 2.63 2.59100 ---00
6 NaN ---00 2.0493 2.2495 ---00 2.0500 2.2400 ---00]
理想情况下,根据您的代码,您每次运行代码时都应该得到2.41 的结果(在问题中给出)。
发生的情况是该页面在后台执行了一些 javascript 授权,然后才填充有效数据。
对于这些类型的页面,最好使用selenium。
from selenium import webdriver
from time import sleep
from bs4 import BeautifulSoup
driver = webdriver.Firefox()
driver.get('https://taripebi.ge/%E1%83%91%E1%83%94%E1%83%9C%E1%83%96%E1%83%98%E1%83%9C%E1%83%98%E1%83%A1-%E1%83%A4%E1%83%90%E1%83%A1%E1%83%94%E1%83%91%E1%83%98')
source = driver.page_source
soup =BeautifulSoup(source, 'lxml')
for paragraph in soup.find('div', style = "width: 40%;/* float: left; */"):
print(paragraph)
输出
1号运行
2.41
第 2 次运行
2.41