我需要從以下鏈接中抓取“2015”和“09/09/2015”:
lacentrale.fr/auto-occasion-annonce-87102353714.html
但由于有很多liand ul,我無法抓取確切的文本。我使用了以下代碼非常感謝您的幫助。
from bs4 import BeautifulSoup
soup = BeautifulSoup(HTML)
soup.find('span', {'class':'optionLabel'}).find_next('span').get_text()
uj5u.com熱心網友回復:
就像@Andrejs回答css selectors中:-soup-contains()提到的那樣。因此,以防萬一,如果涉及到這一點,則需要更多選擇。
生成一個dict所有選項選擇相關值,通過選項標簽作為鍵:
data = dict((e.button.text,e.find_next('span').text) for e in soup.select('.optionLabel'))
資料 lokks 像:
{'Année': '2015', 'Mise en circulation': '09/09/2015', 'Contr?le technique': 'requis', 'Kilométrage compteur': '68 736 Km', 'énergie': 'Electrique', 'Rechargeable': 'oui', 'Autonomie batterie': '190 Km', 'Capacité batterie': '22 kWh', 'Bo?te de vitesse': 'automatique', 'Couleur extérieure': 'gris foncé metal', 'Couleur intérieure': 'cuir noir', 'Nombre de portes': '5', 'Nombre de places': '4', 'Garantie': '6 mois', 'Première main (déclaratif)': 'non', 'Nombre de propriétaires': '2', 'Puissance fiscale': '3 CV', 'Puissance din': '102 ch', 'Puissance moteur': '125 kW', "Crit'Air": '0', 'émissions de CO2': '0 g/kmA', 'Norme Euro': 'EURO6', 'Prime à la conversion': ''}
例子
import requests
from bs4 import BeautifulSoup
headers = {'User-Agent': 'Mozilla/5.0 (X11; CrOS x86_64 8172.45.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.64 Safari/537.36'}
url = 'https://www.lacentrale.fr/auto-occasion-annonce-87102353714.html'
soup = BeautifulSoup(requests.get(url, headers=headers).text)
data = dict((e.button.text,e.find_next('span').text) for e in soup.select('.optionLabel'))
print(data['Année'], data['Mise en circulation'], sep='\n')
輸出
2015
09/09/2015
uj5u.com熱心網友回復:
嘗試:
import requests
from bs4 import BeautifulSoup
headers = {
"User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:100.0) Gecko/20100101 Firefox/100.0"
}
url = "https://www.lacentrale.fr/auto-occasion-annonce-87102353714.html"
soup = BeautifulSoup(requests.get(url, headers=headers).content, "html.parser")
v1 = soup.select_one('.optionLabel:-soup-contains("Année") span')
v2 = soup.select_one(
'.optionLabel:-soup-contains("Mise en circulation") span'
)
print(v1.text)
print(v2.text)
印刷:
2015
09/09/2015
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/478747.html
