Вы можете использовать функцию itertools.takewhile
( официальный документ ), чтобы выполнить то, что вы хотите:
import requests
from bs4 import BeautifulSoup
from itertools import takewhile
link = "https://www.obd-codes.com/p0100"
def fetch_data(link):
res = requests.get(link)
soup = BeautifulSoup(res.text,"lxml")
[script.extract() for script in soup.select("script")]
elems = [i.text for i in takewhile(lambda tag: tag.name != 'h2', soup.select("h2:contains('What does that mean') ~ *"))]
print(elems)
if __name__ == '__main__':
fetch_data(link)
Печать:
['This diagnostic trouble code (DTC) is a generic powertrain code, which means that it applies to OBD-II equipped vehicles that have a mass airflow sensor. Brands include but are not limited to Toyota, Nissan, Vauxhall, Mercedes Benz, Mitsubishi, VW, Saturn, Ford, Jeep, Jaguar, Chevy, Infiniti, etc. Although generic, the specific repair steps may vary depending on make/model.', "The MAF (mass air flow) sensor is a sensor mounted in a vehicle's engine air intake tract downstream from the air filter, and is used to measure the volume and density of air being drawn into the engine. The MAF sensor itself only measures a portion of the air entering and that value is used to calculate the total volume and density of air being ingested.", '\n\n\n\n\xa0', '\n', 'The powertrain control module (PCM) uses that reading along with other sensor parameters to ensure proper fuel delivery at any given time for optimum power and fuel efficiency.', 'This P0100 diagnostic trouble code (DTC) means that there is a detected problem with the Mass Air Flow (MAF)\nsensor or circuit. The PCM detects that the actual MAF sensor frequency signal\nis not performing within the normal expected range of the calculated MAF value.', 'Note: Some MAF sensors also incorporate an air temperature sensor, which is another value used by the PCM for optimal engine operation.', 'Closely related MAF circuit trouble codes include:', '\nP0101 Mass or Volume Air Flow "A" Circuit Range/Performance\nP0102 Mass\nor Volume Air Flow "A" Circuit Low Input\nP0103 Mass\nor Volume Air Flow "A" Circuit High Input\nP0104 Mass or Volume Air Flow "A" Circuit Intermittent\n', 'Photo of a MAF sensor:']
Edit:
Если вы хотите использовать только теги <p>
сразу после тега <h2>
, используйте lambda tag: tag.name == 'p'
.