Как развернуть родителя с помощью красивого супа4 - PullRequest
1 голос
/ 19 июня 2019

Учитывая источник HTML-страницы, такой как:

<html>
  <head></head>
  <body>
    <p><nobr><a href="...">Some link text</a></nobr><p>
  </body>
</html>

И без явного знания, какие теги обертывают элемент <a> (это может быть что угодно, не только nobr).Как создать цикл, который будет разворачивать родительский элемент данного тега <a>, пока его родительский элемент не станет абзацем?

Что-то вроде:

import urllib3
from bs4 import BeautifulSoup as bs

http = urllib3.PoolManager()
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

page = "https://www.snopes.com/fact-check/rebuilding-iraq/"
link="http://www.elca.org/ScriptLib/OS/Congregations/cdsDetail.asp?congrno=12962"

r = http.request('get', page)
body = r.data
soup = bs(body, 'lxml')
a = soup.find('a', href=link)

while True:
    if a.parent.name == "p":
        break
    else:
        a.parent.name.unwrap() #doesnt work as name is string
print(soup)

Ответы [ 2 ]

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

Используйте find_parents для данного дочернего тега.

import requests
from bs4 import BeautifulSoup
page = "https://www.snopes.com/fact-check/rebuilding-iraq/"
link="http://www.elca.org/ScriptLib/OS/Congregations/cdsDetail.asp?congrno=12962"

r = requests.get(page)
soup = bs(r.content, 'lxml')
a = soup.find('a', href=link)

for tag in a.find_parents('p'):
    print(tag)

Вывод:

<p><font class="copyright_text_color" color="" face=""><b>Origins:</b></font>   This item is “true” in the sense that Eric Rydbom is indeed an engineer stationed in Iraq with the Army’s <nobr>4th Infantry</nobr> Division, and he sends monthly <nobr>e-mail</nobr> dispatches such as the one quoted above to fellow members of his congregation at the <nobr><a href="http://www.elca.org/ScriptLib/OS/Congregations/cdsDetail.asp?congrno=12962" target="_blank">First Lutheran</a></nobr> Church of Richmond Beach in Shorline, Washington.  This piece was one of those messages, forwarded to the church’s prayer chain and thence to the larger world via the Internet.</p>

Если вы хотите получить текст, просто используйте.

for tag in a.find_parents('p'):
    print(tag.text)
0 голосов
/ 19 июня 2019

Более простой способ с BS4 4.7.1.это использовать: имеет и атрибут = значение селектора.Нет необходимости в цикле.

import requests
from bs4 import BeautifulSoup as bs

page = "https://www.snopes.com/fact-check/rebuilding-iraq/"
link="http://www.elca.org/ScriptLib/OS/Congregations/cdsDetail.asp?congrno=12962"
r = requests.get(page)
soup = bs(r.content, 'lxml')
print(soup.select_one('p:has([href="' + link + '"])'))
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...