Python:从列表解析仅打印最后一项,不是全部? [英] Python: Parse from list only prints last item, not all?

查看:58
本文介绍了Python:从列表解析仅打印最后一项,不是全部?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码:

from urllib2 import urlopen
from bs4 import BeautifulSoup

url = "https://realpython.com/practice/profiles.html"

html_page = urlopen(url)
html_text = html_page.read()

soup = BeautifulSoup(html_text)

links = soup.find_all('a', href = True)

files = []
base = "https://realpython.com/practice/"


def page_names():
    for a in links:
        files.append(base + a['href'])

page_names()

for i in files:
    all_page = urlopen(i)

all_text = all_page.read()
all_soup = BeautifulSoup(all_text)
print all_soup

解析的前半部分收集了三个链接,后半部分应该打印出所有html.

The first half of the parsing collects three links, the second half is supposed to print out all of their html.

可悲的是,它仅显示最后一个链接的html.

Sadly, it only prints the last link's html.

可能是因为

for i in files:
    all_page = urlopen(i)

它以前使用8行代码为文件中的i提供服务:目的,但我想将其清理并归结为这两行.好吧,显然不是因为它不起作用.

It was working previously with 8 lines of code serving the for i in files: purpose but I wanted to clean it up and got it down to those two. Well, clearly not because it doesn't work.

不过没有错误!

推荐答案

您仅将最后一个值存储在循环中,需要将所有分配和打印内容移入循环中:

You only store the last value in your loop, you need to move all the assignments and the print inside the loop:

for i in files:
    all_page = urlopen(i)
    all_text = all_page.read()
    all_soup = BeautifulSoup(all_text)
    print all_soup

如果要使用函数,我将传递参数并创建列表,否则可能会得到意外的输出:

If you are going to use functions I would pass parameters and create the list otherwise you might get unexpected output:

def page_names(b,lnks):
    files = []
    for a in lnks:
        files.append(b + a['href'])
    return files


for i in page_names(base,links):
    all_page = urlopen(i)
    all_text = all_page.read()
    all_soup = BeautifulSoup(all_text)
    print all_s

您的函数然后可以返回列表理解:

Your function can then return a list comprehension:

def page_names(b,lnks):
    return [b + a['href'] for a in lnks]

这篇关于Python:从列表解析仅打印最后一项,不是全部?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆