2017-03-04 66 views
-1

我的腳本將網頁剪切後生成一個.csv文件,但有些行沒有cuotaa_1cuotaa_2的值。我如何刪除這些行?刪除python中沒有值的行

from urllib.request import urlopen as uReq 
from bs4 import BeautifulSoup as soup 
my_url = 'https://www.betfair.es/sport/football' 
uClient = uReq(my_url) 
page_html = uClient.read() 
uClient.close() 
page_soup = soup(page_html, "html.parser") 
containers = page_soup.findAll("li",{"class":"com-coupon-line avb-row market-1x2 large "}) 

filename = "APUESTAS.csv" 
f = open(filename, "w") 

for container in containers: 
    partidoo = container.div.div.a["data-event"] 

    title_container = container.findAll("li",{"class":"selection sel-0 "}) 
    cuotaa_1 = title_container[0].text.strip() 

    title_container1 = container.findAll("li",{"class":"selection sel-2 "}) 
    cuotaa_2 = title_container1[0].text.strip() 

    enlace0 = container.div.div.a["href"] 
    enlace = "https://www.betfair.es" + enlace0 

回答

0

在python中,空白字符串是「falsey」,所以它們在布爾上下文中被認爲是false。所以,你寫的行,其中cuotaa_1cuotaa_2都具有在容器循環像這樣的結尾內容:

if cuotaa_1 and cuotaa_2: 
    f.write("{},{}\n".format(cuotaa_1,cuotaa_2))