Как получить доступ к тегу под тегом заголовка (т.е. <h1>) с помощью bs4 / python - PullRequest
0 голосов
/ 05 января 2019

У меня есть некоторые проблемы с попаданием тега под тег заголовка (h1, h2 и т. Д.).

возьми эту страницу:

https://www.w3schools.com/python/ref_string_split.asp

допустим, я хочу получить текст в заголовке "определения и использования",

`<h2>Definition and Usage</h2>`

как мне сослаться на блок <p> непосредственно под этой строкой?

Ответы [ 3 ]

0 голосов
/ 05 января 2019

Допустим, вы можете добраться до <h2>Definition and Usage</h2> с soup.find_all('h2')[7]

Теперь элемент p связан с вышеуказанным элементом, который можно извлечь с помощью soup.find_all('h2')[7].next_sibling.next_sibling Это приводит к

<p>The <code class="w3-codespan">split() метод разбивает строку на список.

Примечание: мы используем 2 .next_sibling, поскольку первый брат <h2>Definition and Usage</h2> является новой строкой, т.е. \n

Оформление заказа об официальном использовании beautifulsoup doc

0 голосов
/ 05 января 2019

Вы можете использовать find_next , чтобы получить следующий тег.

from bs4 import BeautifulSoup
import requests
res=requests.get("https://www.w3schools.com/python/ref_string_split.asp")
soup=BeautifulSoup(res.text,"html5lib")
h2=soup.find("h2", string="Definition and Usage")
p_after_h2=h2.find_next("p")
p_text_after_h2=p_after_h2.text.replace("\n","")
print(p_after_h2)
print(p_text_after_h2)

выход

<p>The <code class="w3-codespan">split()</code> method splits a string into a 
list.</p>
The split() method splits a string into a list.

HTML-код страницы

...
<div class="w3-example">
  <h3>Example</h3>
  <p>Split a string into a list where each word is a list item:</p>
  <div class="w3-code notranslate pythonHigh">
    txt = &quot;welcome to the jungle&quot;<br><br>x = txt.split()<br><br>
    print(x)</div>
  <a target="_blank" class="w3-btn w3-margin-bottom" href="showpython.asp?filename=demo_ref_string_split">Run example &raquo;</a>
</div>

<hr>

<h2>Definition and Usage</h2>

<p>The <code class="w3-codespan">split()</code> method splits a string into a 
list.</p>
<p>You can specify the separator, default separator is any whitespace.</p>
<div class="w3-panel w3-note">
  <p><strong>Note:</strong> When max is specified, the list will contain the 
  specified number of elements <em>plus one</em>.</p>
</div>

<hr>

<h2>Syntax</h2>

<div class="w3-code w3-border notranslate">
  <div>
    <em>string</em>.split(<em>separator, max</em>)
  </div>
</div>
...

Это наш ответный текст. Использование

h2=soup.find("h2", string="Definition and Usage")

мы получаем тег h2 с "Definition and Usage" внутри него. Затем мы находим следующий p после этого тега h2, используя

p_after_h2=h2.find_next("p")

Наконец мы используем

p_text_after_h2=p_after_h2.text.replace("\n","")

получить текст в теге p после удаления перевода строки.

0 голосов
/ 05 января 2019

Вы можете выбрать весь блок тегов, в который он вложен, и затем использовать 2 функции .split ():

import lxml
from bs4 import BeautifulSoup


CHROME_PATH = 'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe'
CHROMEDRIVER_PATH = 'chromedriver.exe'
WINDOW_SIZE = "1920,1080"

chrome_options = Options()

chrome_options.add_argument("--log-level=3")
chrome_options.add_argument("--headless")
chrome_options.add_argument("--window-size=%s" % WINDOW_SIZE)

chrome_options.binary_location = CHROME_PATH

url = "Your Url" # Replace with your url
browser = webdriver.Chrome(executable_path=CHROMEDRIVER_PATH, chrome_options=chrome_options)
browser.get(url)
innerHTML = browser.execute_script("return document.body.innerHTML")
soup = BeautifulSoup(str(innerHTML.encode('utf-8').strip()), 'lxml')

# Identify the enclosing tag that will contain your <h2> tags (before the p)
source = soup.find('name of tag containing h2')
html = str(source).split("</p>")[0]
html = html.split("<h2>Definition and Usage</h2><p>")[1]

# This should give you everything between the tags that you specified.

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