[英]Dont Want Spaces Between Paragraphs : Python
我正在使用以下代碼抓取新聞網站以獲取新聞文章:
import mechanize
from selenium import webdriver
from bs4 import BeautifulSoup
url = "http://www.thehindu.com/archive/web/2012/06/19/"
link_dictionary = {}
driver = webdriver.Firefox()
driver.get(url)
soup = BeautifulSoup(driver.page_source)
for tag_li in soup.findAll('li', attrs={"data-section":"Editorial"}):
for link in tag_li.findAll('a'):
link_dictionary[link.string] = link.get('href')
print link_dictionary[link.string]
urlnew = link_dictionary[link.string]
brnew = mechanize.Browser()
htmltextnew = brnew.open(urlnew).read()
articletext = ""
soupnew = BeautifulSoup(htmltextnew)
for tag in soupnew.findAll('p'):
articletext += tag.text
print articletext
driver.close()
我得到了理想的結果,但我想要一條特定的新聞文章。 對於一些文章,我將整篇文章放在一行,而在其他文章中,我得到不同的段落。 有人可以幫我解決問題嗎? 我是python編程的新手。 感謝致敬。
這可能與特定網站的HTML中管理空白的方式有關,並且並非所有網站都會對其內容使用“p”標記。 你最好的選擇是做一個正則表達式替換,它可以消除多余的空格(包括換行符)。
在文件的開頭,導入正則表達式模塊 :
import re
然后在構建文章文本后,添加以下代碼:
print re.sub('\s+', ' ', articletext, flags=re.M)
您可能還想從其中可能包含的其他元素中提取文本。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.