Как искать lxml после ключевого слова, используя python - PullRequest
0 голосов
/ 01 ноября 2019

У меня есть веб-скребок, который очищает страницы со многими разделами информации, используя bs4. Так как многие разделы повторяют div class, это трудно очистить. Я пытаюсь найти способ заставить его начать поиск lxml после определенной фразы в html. Есть ли способ сделать это?

ниже приведен небольшой пример того, с чем я работаю, пытаясь получить что-то вроде table_soup, чтобы начать после определенной фразы.

from bs4 import BeautifulSoup
import csv
import re

# Making get request
r = requests.get('https://m.the-numbers.com/movie/Black-Panther')

# Creating BeautifulSoup object
soup = BeautifulSoup(r.text, 'lxml')

# Localizing table from the BS object
table_soup = soup.find('div', class_='row').find('div', class_='table-responsive').find('table', id='movie_finances')
website = 'https://m.the-numbers.com/'


# Iterating through all trs in the table except the first(header) and the last two(summary) rows 
for tr in table_soup.find_all('tr')[1:6]:
    tds = tr.find_all('td')
    title = tds[0].text.strip()

    # make sure that home market performance doesnt check the second one
    if title != 'Home Market Performance':
        details.append({
            'title': title,
            'amount': tds[1].text.strip(),
        })

summary_soup = soup.find('div', id='summary').find('div', class_='table-responsive').find('table', class_='table table-sm')
summaryList = []
for tr in summary_soup.find_all('tr')[1:4]:
    tdmd = tr.find_all('td')

    summaryList.append({
        'unit': tdmd[1].text.strip(),
    })```

1 Ответ

0 голосов
/ 01 ноября 2019
from bs4 import BeautifulSoup
import requests
import csv
import re

r = requests.get('https://m.the-numbers.com/movie/Black-Panther')
soup = BeautifulSoup(r.text, 'lxml')
# If you have an unique id for the table you can directly access the table using that id
table_soup = soup.find('table', id='movie_finances')
table_soup.find_all('tr')
# this will get the 4 tr tags in the body. No need to use slicing.

summary_soup = soup.find('div',id="summary").find('div').find_all('div')[3].find('table')

как тег 'td', являющийся дочерним элементом с текстом, найдите его и получите для родительского элемента доступ к заголовку и значению

prod_budget_tag, value_tag = summary_soup.find('td', text=u"Production\xa0Budget:").find_parent('tr').find_all('td')

print prod_budget_tag.text, value_tag.text

Аналогичным образом вы можете получить другие поля и значения из таблицы.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...