簡體   English   中英

for 循環返回空值

[英]for loop returning empty values

因此,以下代碼工作正常,用於在某個日期(即 01/04/2017)進行網絡抓取報紙,但是當我創建日期范圍並每天循環時,我會在代碼下方獲得空值,然后我把“for循環”

url = 'http://servicios.lanacion.com.ar/archivo-f01/04/2017-c30'
sauce = uReq(url)
soup = bs.BeautifulSoup(sauce,'html.parser')
date = soup.findAll('div',{'class':'titFecha'})
date = str(date)
fecha = '"titFecha">'
date = date[date.find(fecha)+len(fecha):date.find(fecha)+21]
day = date[:2]
month = date[3:5]
year = date[6:12]
print date

filename = 'La Nacion_%s_%s_%s.csv' % (day, month, year)
f = open(filename,'w')
headers = "Date, Title, Encabezado\n"
f.write(headers)

acumulados = soup.findAll('li',{'class':'acumulados'})
for acum in acumulados:
    title =  acum.a['href']
    #     title = title.text
    print title
    encabezado = acum.p
    #     encabezado = encabezado.text
    print encabezado,'\n'
    f.write(str(date) + ',' + str(title).replace(',',' ') + ',' + str(encabezado).replace(',',' ') + '\n')

f.close()

這是循環,可能很容易,但我正在學習,仍然沒有看到這些問題,謝謝!

date_range = pd.date_range('2017-04-01',periods=2, freq='d')
date_range = date_range.strftime("%d/%m/%y")
for i in date_range:
    url = 'http://servicios.lanacion.com.ar/archivo-f%r-c30' % i
    sauce = uReq(url)
    soup = bs.BeautifulSoup(sauce,'html.parser')
    date = soup.findAll('div',{'class':'titFecha'})
    date = str(date)
    fecha = '"titFecha">'
    date = date[date.find(fecha)+len(fecha):date.find(fecha)+21]
    day = date[:2]
    month = date[3:5]
    year = date[6:12]
    print date

    filename = 'La Nacion_%s_%s_%s.csv' % (day, month, year)
    f = open(filename,'w')
    headers = "Date, Title, Encabezado\n"
    f.write(headers)

    acumulados = soup.findAll('li',{'class':'acumulados'})
    for acum in acumulados:
        title =  acum.a['href']
        print title
        encabezado = acum.p
        print encabezado,'\n'
        f.write(str(date) + ',' + str(title).replace(',',' ') + ',' + str(encabezado).replace(',',' ') + '\n')
f.close()

for 循環中 i 的格式是 numpy.string_ 不是字符串,你可以將url行中的%r更改為%s ,並將strftime("%d/%m/%y")更改為strftime("%d/%m/%Y")如下:

date_range = pd.date_range('2017-04-01',periods=2, freq='d')
date_range = date_range.strftime("%d/%m/%Y")
for i in date_range:    
    url = 'http://servicios.lanacion.com.ar/archivo-f%s-c30' % i

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM