[英]How to remove \n from the middle of texts in a list of texts in python
我在網頁上搜索了源代碼中包含以下表單的標題列表:
<h2 class="story-heading"><a href="somelink.html">Crash Highlights
Indonesia’s Poor Air
Safety Record</a><span class="product-label theme-nyt-now "><span class="visually-hidden">NYT Now</span><i class="icon dot-logo-icon"></i></span></h2>
我只想要文字。
我得到以下列表:
[u'Crash Highlights\nIndonesia\u2019s Poor Air\nSafety RecordNYT Now', u'Palestine Joins\nHague Criminal\nCourt, Risking\nU.S. SanctionsNYT Now', ... ]
每個字符串都有"\\n"
字符,以"NYT Now"
結尾如何刪除NYT Now? 據我所知, get_text()
只應該檢索<a>
選項卡中的函數
這是我的代碼:
url="<website link>"
html = urllib2.urlopen(url)
soup = BeautifulSoup(html,'lxml')
headings_list=[]
for heading in soup.find_all(class_="story-heading"):
for text in heading.find_all('a'):
headings_list.append(heading.get_text().strip())
print headings_list
我認為這應該做你想要的:
heading.get_text().replace('\n',' ').replace('NYT Now', '')
采用
headings_list.append(heading.get_text().strip()[:-7])
采取沒有最后7個字符的標題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.