Страницы «цитат», которые вы хотите очистить, содержат несколько неполных / висячих HTML-тегов. Это может быть проблематично для анализа, если вы не понимаете используемый вами синтаксический анализатор. Чтобы получить подсказку о них, см. эту страницу .
Теперь вернемся к коду, для моего удобства я использовал парсер lxml
. В дальнейшем, если вы посмотрите на источник страницы любой из этих страниц «цитат», то увидите, что большая часть текста, который вы хотите очистить, присутствует в одном из следующих тегов: {h3
, p
ul
ol
}. Также обратите внимание, что рядом с каждым тегом h3
стоит строка. Эта строка может быть захвачена с помощью .next_sibling
.
Теперь, когда условия установлены, давайте перейдем к коду.
import bs4
from urllib.request import Request,urlopen as uReq, HTTPError
#Import HTTPError in order to avoid the links with no content/resource of interest
from bs4 import BeautifulSoup as soup_
import re
#define url of interest
my_url = 'http://archive.ontheissues.org/Free_Trade.htm'
#Creating a function to harness the power of scraping frequently
def make_soup(url):
# set up known browser user agent for the request to bypass HTMLError
req=Request(url,headers={'User-Agent': 'Mozilla/5.0'})
#opening up connection, grabbing the page
uClient = uReq(req)
page_html = uClient.read()
uClient.close()
#html is jumbled at the moment, so call html using soup function
soup = soup_(page_html, "lxml")
return soup
# Test: print title of page
#soup.title
soup = make_soup(my_url)
tags = soup.findAll("a" , href=re.compile("javascript:pop\("))
#print(tags)
# get list of all URLS
for links in tags:
link = links.get('href')
if "java" in link:
print("http://archive.ontheissues.org" + link[18:len(link)-3])
main_url = "http://archive.ontheissues.org" + link[18:len(link)-3]
try:
sub_soup = make_soup(main_url)
content_collexn = sub_soup.body.contents #Splitting up the page into contents for iterative access
#text_data = [] #This list can be used to store data related to every person
for item in content_collexn:
#Accept an item if it belongs to the following classes
if(type(item) == str):
print(item.get_text())
elif(item.name == "h3"):
#Note that over here, every h3 tagged title has a string following it
print(item.get_text())
#Hence, grab that string too
print(item.next_sibling)
elif(item.name in ["p", "ul", "ol"]):
print(item.get_text())
except HTTPError: #Takes care of missing pages and related HTTP exception
print("[INFO] Resource not found. Skipping to next link.")
#print(text_data)