beautifulsoup пропускает остальную часть веб-страницы

#python #web-scraping #beautifulsoup

#python #очистка веб-страницы #beautifulsoup

Вопрос:

У меня есть веб-страница, которая является этой: southafricatoday

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

введите описание изображения здесь

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

     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
  

Комментарии:

1. Чтобы уточнить, объект запроса (page_content) содержит все теги, но BS4, похоже, не находит их при синтаксическом анализе?

2. @JacobKern, да.

Ответ №1:

Это из-за этого 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. Спасибо @ SIM, да, я думаю, это из-за синтаксического анализатора «html.parse».

Ответ №2:

Да, это странно. Мне придется взглянуть на теги более внимательно, поскольку я собираюсь отойти, но просто для начала (так что не самый красноречивый или эффективный), но вы можете получить этот первый тег, затем начать поиск следующих <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!