我想用beautifulsoup 提取pourcentage 值。我試圖獲取頁面上的所有值,但它總是回傳 0%。
我想廢棄這個值:

在這個網站上。
這是我獲取所有 pourcentage 值的代碼:
import requests
from bs4 import BeautifulSoup
URL = "https://www.horoscope.fr/horoscopes/aujourdhui/scorpion"
page = requests.get(URL)
soup = BeautifulSoup(page.content, "html.parser")
results = soup.find(id="ResultsContainer")
trucs = soup.find_all('strong')
for truc in trucs:
print(truc.text)
我明白了:
0%
0%
0%
0%
0%
0%
15 € les 10 minutes
Gui
Apple cobbler
我怎樣才能提取價值?
uj5u.com熱心網友回復:
開個玩笑,這是獲取星座值的一種方法(您最終可以將它們映射到 1-6 比例的百分比):
import requests
from bs4 import BeautifulSoup as bs
import pandas as pd
import json
headers = {
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.5112.79 Safari/537.36'
}
url = 'https://www.horoscope.fr/horoscopes/aujourdhui/scorpion'
r = requests.get(url, headers=headers)
soup = bs(r.text, 'html.parser')
data = json.loads(soup.select_one('script[id="__NEXT_DATA__"]').text)
magic_stuffs = data['props']['pageProps']['initialProps']['horoscope']['overviews']
df = pd.json_normalize(magic_stuffs)
print(df)
結果在終端:
rating title iconUrl titleColor anchorId
0 5 AMOUR https://cdn.tlmq.fr/mbe/horoscope/rating_5_v1.png #000 love
1 2 TRAVAIL https://cdn.tlmq.fr/mbe/horoscope/rating_2_v1.png #000 career
2 4 BIEN-êTRE https://cdn.tlmq.fr/mbe/horoscope/rating_4_v1.png #000 wellbeing
3 5 VIE SOCIALE https://cdn.tlmq.fr/mbe/horoscope/rating_5_v1.png #000 social_life
4 4 AMBIANCE https://cdn.tlmq.fr/mbe/horoscope/rating_4_v1.png #000 mood
5 2 FINANCES https://cdn.tlmq.fr/mbe/horoscope/rating_2_v1.png #000 finances
您可以將整數值映射到顯示的百分比(5 分是 83%,2 是 33%,依此類推)。
這些百分比是由頁面中執行的 javascript 動態顯示的,因此 Requests 看不到它們,bs4 也無法決議它們。
請求的相關檔案:https ://requests.readthedocs.io/en/latest/
對于熊貓:https ://pandas.pydata.org/docs/
對于 BeautifulSoup:https ://beautiful-soup-4.readthedocs.io/en/latest/
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/530370.html
上一篇:如何使用R語言抓取多頁網站
下一篇:如何跳過bs4標簽內的一些迭代?
