gpt4 book ai didi

python - 如何导航美丽汤中的特定标签?

转载 作者:太空宇宙 更新时间:2023-11-03 21:19:47 25 4
gpt4 key购买 nike

我想导航网站上的特定标签。在这个网站上,很少有像这样的标签我只想浏览其中之一。每次运行代码时我都会得到不同的输出。

import bs4 as bs
import urllib

source = urllib.urlopen("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").read()
soup = bs.BeautifulSoup(source, 'lxml')

for paragraph in soup.find('div', style = "width: 40%;/* float: left; */"):
print(paragraph)

最佳答案

每次运行代码时,我都会得到不同的输出。

是的。每次页面返回不同的结果。即使您的选择是错误的,也不能解释您每次都会打印不同的结果。我运行了几次,每次都得到不同的结果。

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)

输出

运行1号

[    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 结果。

enter image description here

发生的情况是,该页面在后台执行一些 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

关于python - 如何导航美丽汤中的特定标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54388095/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com