我只想獲取任何網站頁面內容的文本。我正在使用BeautifulSoup來做到這一點。使用BeautifulSoup從網站中提取文本
我寫了一個函數象下面這樣:
def textClean(text):
""" This function takes the input text and cleans the HTML tags from it
"""
from bs4 import BeautifulSoup
souptext=BeautifulSoup(text)
print text
print souptext.get_text()
這將打印原始的HTML源代碼,然後那太文本。
但是這裏是一個示例輸出,我得到:
HTML輸出:(第一print語句)
<p><img style="float:right;" src="http://static4.businessinsider.com/image/56eb68e791058427008b72e5-907-680/5550538407_c22babffba_b.jpg" alt="radar" data-mce-source="US Navy" data-mce-caption="Mineman Seaman Charles Bryan watches for contacts on the SPA 256 radar while on watch in the Combat Directive Center aboard the mine countermeasures ship USS Ardent (MCM 12)." data-link="https://www.flickr.com/photos/usnavy/5550538407/in/photolist-9stXG4-e6i1uU-e6i1tE-dLSiBQ-c9jmg7-f5LbtS-r9jw69-efvjaN-duNiV6-efpeEP-eW8Dg9-q1nZiQ-en2osX-duNiTa-njkj3s-eep3Mb-kUdU5g-9d7u4E-eeoYiC-fr2CuX-axHdte-fsVD3D-drHPeJ-9rAVac-cnMSiW-9vVcbN-enB31b-f23pKF-aBjveY-9rEhwY-9u6GZy-9rDT9L-bojAAh-9uiNiU-9AJSrB-9rFxwQ-bjkanD-aefpN9-ea2WB2-ea2WyR-a1tUoa-9rAUXZ-ea8Bf9-9Wm3Z8-9rNE7o-enB1YY-9rAUHX-ea2WpF-aNR7eD-9NX2pq" /><span class="source">US Navy</span></p><p>The United States has seen Chinese activity around a reef that China seized from the Philippines nearly four years ago that could be a precursor to more land reclamation in the disputed South China Sea, the U.S. Navy chief said on Thursday.</p>
二TET輸出:(第二個print語句)
US NavyThe United States has seen Chinese activity around a reef that China seized from the Philippines nearly four years ago that could be a precursor to more land reclamation in the disputed South China Sea, the U.S. Navy chief said on Thursday.
如果你看到
<span class="source">US Navy</span></p>
標籤之間的文字也越來越提取,我不希望我們彷彿看到原來的文章(以下鏈接),文本不是原始文章的一部分。我知道get_text()會獲取所有文本,所以我想要一個簡單的解決方案,我們可以指定提取段落標籤之間的文本,但不包括span標籤,因爲我不認爲span標籤中的文本是零件的原文。
這裏是我使用的文章的鏈接。
EDIT1:
獲取輸出是這樣的:每一列被轉換爲Unicode。
這裏是我寫的映射函數代碼,用於映射Spark DataFrame的每條記錄,並清除數據框'desc'列中的HTML標記。
def htmlParsing(x):
""" This function takes the input text and cleans the HTML tags from it
"""
from bs4 import BeautifulSoup
#print text
row=x.asDict()
textcleaned=''
souptext=BeautifulSoup(row['desc'])
#souptext=BeautifulSoup(text)
p_tags=souptext.find_all('p')
for p in p_tags:
if p.string:
#textcleaned+=p.string
ret_list= (int(row['id']),(row['title']),(p.string))
return ret_list
#print p.string
sdf_cleaned=sdf_rss.map(htmlParsing)
sdf_cleaned.take(4)
[(-33753621, 蘇格蘭u'Royal銀行正在測試可以解決您的銀行問題的機器人(RBS)」, u'If你討厭使用銀行櫃檯或客戶服務代表,然後'), (-761323061, )你的性別色情正在促使對兒童色情法律進行徹底檢查', u'Rampant青少年性行爲已經讓政治家和執法機構圍繞着國家正在努力尋找起訴學生爲兒童色情和讓他們脫身的某種法律中間地帶。'), (1405376555, 經過進一步的審查,中國已經開始在南中國海建設一個新項目, u美國已經看到中國在四年前從菲律賓掠奪中國的一塊礁石上開展的活動,這可能是美國海軍總司令週四表示,在有爭議的南中國海進行更多的填海工程。'), (-1882022821, u'Ingition鎖定法律正在降低酒後駕駛死亡率, u'Reuters健康狀況 - 要求定罪醉酒司機在他們的汽車中安裝點火聯鎖裝置的州有15%的下降相比於沒有這些要求的國家,研究表明,酒精相關的撞車死亡。')]
這是一個很好的答案。但是我不想打印字符串。我想將其保存爲數據集。但是,當我將它保存回來時,我確實將unicode'u'添加到它並且不是純字符串。我如何擺脫這些? – Baktaawar
你可以發佈你保存數據代碼的問題嗎? –
檢查編輯您的。 – Baktaawar