Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/314.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使用bs4消除文本上方的空白_Python_Python 3.x_Parsing_Python Requests_Bs4 - Fatal编程技术网

Python 如何使用bs4消除文本上方的空白

Python 如何使用bs4消除文本上方的空白,python,python-3.x,parsing,python-requests,bs4,Python,Python 3.x,Parsing,Python Requests,Bs4,好的,我正在使用bs4(BeautifulSoup)解析一个网站,并找到我正在寻找的特定标题。我的代码如下所示: import requests from bs4 import BeautifulSoup url = 'http://www.ewn.co.za/Categories/Local' r = requests.get(url).text soup = BeautifulSoup(r) for i in soup.find_all(class_='article-short'):

好的,我正在使用bs4(BeautifulSoup)解析一个网站,并找到我正在寻找的特定标题。我的代码如下所示:

import requests
from bs4 import BeautifulSoup
url = 'http://www.ewn.co.za/Categories/Local'
r = requests.get(url).text
soup = BeautifulSoup(r)
for i in soup.find_all(class_='article-short'):
    if i.a:
        print(i.a.text.replace('\n', '').strip())
    else:
        print(i.contents[0].strip())

这段代码可以工作,但在输出中,它首先显示20行空白,然后再从网站打印请求的标题。我的代码是否有问题,或者我可以做些什么来消除空白?

因为您有如下元素:

<article class="article-short">
<div class="thumb"><a href="http://ewn.co.za/2016/05/14/Contralesa-against-scrapping-initiation-due-to-cold-weather"><img alt="FILE: Boys who have undergone a circumcision ceremony walk near Qunu in the Eastern Cape in 2013. Picture: AFP." height="147" src="http://ewn.co.za/cdn/-%2fmedia%2f3C37CB28056746CD95FC913757AAD41C.ashx%3fas%3d1%26h%3d147%26w%3d234%26crop%3d1;waeb9b8157b3e310df" width="234"/></a></div>
<h6 class="h6-mega"><a href="http://ewn.co.za/2016/05/14/Contralesa-against-scrapping-initiation-due-to-cold-weather">Contralesa against scrapping initiation due to cold weather</a></h6>
</article>

使用strip函数可以删除字符串()中的空白