Проблема извлечения некоторого контента с веб-страницы с помощью BeautifulSoup - PullRequest
1 голос
/ 06 июня 2019

Я создал скрипт, использующий python вместе с библиотекой BeautifulSoup для очистки определенного контента с веб-страницы. Интересующий меня контент находится под What does that mean на этой странице.

Ссылка на эту страницу

Если быть более точным - содержимое, которое я хотел бы проанализировать:

Все под этим названием What does that mean, за исключением изображения.

Это то, что я до сих пор пытался схватить:

import requests
from bs4 import BeautifulSoup

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")]
    elem = [item.text for item in soup.select("h2:contains('What does that mean') ~ p")]
    print(elem)

if __name__ == '__main__':
    fetch_data(link)

Однако способ, который я пробовал, дает мне почти все с той страницы, чего я не ожидаю.

Как я могу получить контент в диапазоне от What does that mean до What are some possible symptoms с указанной выше страницы?

PS Я не хочу делать это с помощью регулярных выражений.

Ответы [ 2 ]

2 голосов
/ 06 июня 2019

Вы можете использовать функцию 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'.

1 голос
/ 06 июня 2019

Есть еще один способ добиться того же. Пусть ваш сценарий продолжает работать, пока не встретит этот тег h2.

import requests
from bs4 import BeautifulSoup

url = "https://www.obd-codes.com/p0100"

res = requests.get(url)
soup = BeautifulSoup(res.text,"lxml")
[script.extract() for script in soup.select("script")]
elem_start = [elem for elem in soup.select_one("h2:contains('What does that mean')").find_all_next()]
content = []
for item in elem_start:
    if item.name=='h2': break
    content.append(' '.join(item.text.split()))
print(content)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...