BeautifulSoup пропускает остальную часть веб-страницы - PullRequest
0 голосов
/ 20 марта 2019

У меня есть веб-страница: southafricatoday

На этой странице между тегами есть пустые теги, такие как <p><\p>.Что я заметил, так это то, что bs4 пропускает чтение остальной части страницы (после этих пустых тегов).

enter image description here

Все теги после красной стрелкипропустил.

    import urllib.request as urllib2
    from urllib.request import Request
    import bs4
    url = 'https://southafricatoday.net/world-news/europe/damage-to-insured-property-during-yellow-vests-protests-soars-to-over-220mln/'  # row['link']
    page = Request(url, headers={'User-Agent': 'Mozilla/4.61 [en] (Win32; Escape 4.8; U)'})
    page_content = urllib2.urlopen(page).read()
    soup = bs4.BeautifulSoup(page_content, "html.parser")
    productDivs = soup.findAll('div', attrs={'class': 'td-post-content'})

    productDivs = productDivs[0].contents
    productDivs = [tag for tag in productDivs if not isinstance(tag, bs4.element.NavigableString)]
    x = productDivs[1]
    tags = x.findChildren(recursive=False) # check the tags here

Ответы [ 2 ]

2 голосов
/ 20 марта 2019

Это из-за этого html.parser. Чтобы решить эту проблему, попробуйте изменить html.parser либо lxml, либо html5lib.

import requests
from bs4 import BeautifulSoup

url = 'https://southafricatoday.net/world-news/europe/damage-to-insured-property-during-yellow-vests-protests-soars-to-over-220mln/'

response = requests.get(url, headers={'User-Agent': 'Mozilla/5.0'})
soup = BeautifulSoup(response.text, 'lxml')
for ptagContent in soup.find(itemprop="articleBody").find_all("p"):
    print(ptagContent.text)
1 голос
/ 20 марта 2019

Да, это странно. Мне придется взглянуть на теги более внимательно, так как я собираюсь отступить, но только в качестве первого шага (поэтому не самый красноречивый или эффективный), но вы можете получить этот первый тег, а затем начать искать эти следующие <p> тегов, поместите их в список, затем объедините их, чтобы получить полный вывод:

import requests
import bs4

headers={'User-Agent': 'Mozilla/4.61 [en] (Win32; Escape 4.8; U)'}
url = 'https://southafricatoday.net/world-news/europe/damage-to-insured-property-during-yellow-vests-protests-soars-to-over-220mln/'
response = requests.get(url, headers=headers)

soup = bs4.BeautifulSoup(response.text, 'html.parser')
productDivs = soup.find_all('div', {'class':'td-post-content'})

article = ' '.join([ each.text.strip() for each in productDivs[0].find_next('p').find_next('p').parent.find_all('p') ])

Выход:

print (article)
On Monday, the French Insurance Federation (FFA) reported 170 million euros in losses, however, this figure did not include losses caused by protests that took place on 16 March that were accompanied by serious disorder in the country. The newspaper Figaro reported that on Tuesday, Le Maire announced during hearings in the country’s parliament that overall losses, including from Saturday’s unrest, amounted to 200 million euros. READ MORE: France’s New Bid to Suppress Yellow Vest Protests Likely to ‘Help the Movement’ The wave of the yellow vests rallies — named after the obligatory attribute of French drivers — started in France in mid-November. The protests have been marked by violence and public disorder. While the French government ultimately abandoned plans to raise the fuel taxes that triggered the rallies in the first place, and introduced other measures to improve the country’s socioeconomic situation, the protests have continued and morphed into a broader movement against French President Emmanuel Macron’s economic policies and high living costs.  Sputnik News
South Africa Today – World News – Europe Join our mailing list to receive news every day Your email is safe with us. We hate spam too!
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...