我正在尝试制作一个程序,从本新闻网站档案的每一页上的每篇文章中解析正文文本。最初,我的程序停在第32行,我打印了每个链接并将它们保存到CSV文件中,并且有效。现在,我想打开每个链接,并将文章的主体文本保存到CSV文件中。我尝试使用与最初使用BeautifulSoup相同的代码格式,但现在我的代码没有打印任何东西。我不知道我的问题是否是我如何使用美丽的小组或如何编写网站HTML的标签。这是档案网站:https://www.politico.com/newsletters/playbook/archive(其中有408页(
from bs4 import BeautifulSoup
from urllib.request import urlopen
csvFile = 'C:/Users/k/Dropbox/Politico/pol.csv'
with open(csvFile, mode='w') as pol:
csvwriter = csv.writer(pol, delimiter='|', quotechar='"', quoting=csv.QUOTE_MINIMAL)
#for each page on Politico archive
for p in range(0,409):
url = urlopen("https://www.politico.com/newsletters/playbook/archive/%d" % p)
content = url.read()
#Parse article links from page
soup = BeautifulSoup(content,"lxml")
articleLinks = soup.findAll('article', attrs={'class':'story-frag format-l'})
#Each article link on page
for article in articleLinks:
link = article.find('a', attrs={'target':'_top'}).get('href')
#Open and read each article link
articleURL = urlopen(link)
articleContent = articleURL.read()
#Parse body text from article page
soupArticle = BeautifulSoup(articleContent, "lxml")
#Limits to div class = story-text tag (where article text is)
articleText = soup.findAll('div', attrs={'class':'story-text'})
for div in articleText:
#Limits to b tag (where the body text seems so exclusively be)
bodyText = div.find('b')
print(bodyText)
#Adds article link to csv file
csvwriter.writerow([bodyText])
我希望输出在存档中打印每篇文章的正文文本,并将其全部保存到CSV文件中。
它没有打印任何东西,因为您在 articleText = soup.findAll('div', attrs={'class':'story-text'})
您将其存储为soupArticle
,而不是soup
。
您还想要文本还是HTML元素?按照原样,您将获得标签/元素。如果您只需要文字,则需要bodyText = div.find('b').text
但是主要问题是要更改:
articleText = soup.findAll('div', attrs={'class':'story-text'})
to
articleText = soupArticle.findAll('div', attrs={'class':'story-text'})
要获取完整的文章,您必须循环浏览p
标签。并弄清楚如何跳过您不需要的零件。有一种更好的方法,但是要让您前进,类似的事情:
for article in articleLinks:
link = article.find('a', attrs={'target':'_top'}).get('href')
articleURL = urlopen(link)
articleContent = articleURL.read()
soupArticle = BeautifulSoup(articleContent, "lxml")
articleText = soupArticle.findAll('div', attrs={'class':'story-text'})
for div in articleText:
bodyText = div.find_all('p')
for para in bodyText:
if 'By ' in para.text:
continue
print (para.text.strip())