【问题标题】:Python: Parse from list only prints last item, not all?Python:从列表中解析只打印最后一项,而不是全部?
【发布时间】:2015-04-19 18:18:51
【问题描述】:

我的代码:

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。

遗憾的是,它只打印最后一个链接的 html。

可能是因为

for i in files:
    all_page = urlopen(i)

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

没有错误!

【问题讨论】:

    标签: python parsing for-loop printing beautifulsoup


    【解决方案1】:

    你只存储循环中的最后一个值,你需要移动循环内的所有赋值和打印:

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

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

    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
    

    然后你的函数可以返回一个列表推导:

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

    【讨论】:

      【解决方案2】:

      在您的 for 循环中,您将分配给 all_page,这将在每个循环中覆盖它,因此它只会具有最后一次迭代的值。

      如果您希望它为每个页面打印 all_soup,您也可以将这 3 行缩进到 for 循环内,然后每次循环都会执行它们。

      【讨论】:

        【解决方案3】:

        这似乎只是一个格式问题,你可能是想在循环中打印它,对吧?

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-10-19
          • 1970-01-01
          • 2015-09-16
          相关资源
          最近更新 更多