[英]How to get text with line breaks that match the browser view rather than the html source (using python and beautifulsoup)
[英]How to print html without breaks using python, beautifulsoup?
我正在嘗試使用beautifulsoup這樣打印html:
load = urllib2.urlopen(url)
soup = BeautifulSoup(load, 'lxml')
characteristics = soup.find('table', { 'class' : 'characteristics-table'})
print characteristics
得到這個:
<table class="characteristics-table">
<tr class="characteristics alt">
<td class="name">
Zīmols
</td>
<td>
Emporio Armani</td>
</tr>
<tr class="characteristics">
<td class="name">
<b>Mehānisma tips</b>
</td>
<td>
<b>Mehāniskie automātiskie</b></td>
</tr>...
但是需要這樣的東西:
<table class="characteristics-table"><tr class="characteristics alt"><td class="name">Zīmols</td><td>...
怎么做?
如果只想刪除characteristics
中的換行符,則使用str.replace
來刪除它們,方法是用空字符串''
替換換行符:
print str(characteristics).replace('\n', '').replace('\r\n', '')
第一個替換unix樣式的換行符,第二個應用於第一個結果,替換Windows樣式的換行符。
編輯: .replace
必須應用於beautifulsoup的查找返回的obj的str()
。
''.join(characteristics.split('\n')) #or \r\n on Windows
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.