[英]Python: Parse from list only prints last item, not all?
我的代碼:
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行代碼為文件中的i提供服務:目的,但我想將其清理並歸結為這兩行。 好吧,顯然不是因為它不起作用。
沒錯!
您只需將最后一個值存儲在循環中,就需要在循環內移動所有分配和打印內容:
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]
在for循環中,您要遍歷all_page,它將在每次循環中覆蓋它,因此它將僅具有上一次迭代的值。
如果您希望它為每頁打印all_soup,則只需將這3行縮進到for循環中,那么它們將在每次循環中執行。
似乎是格式問題,您可能打算在循環中打印它,對吧?
for i in files:
all_page = urlopen(i)
all_text = all_page.read()
all_soup = BeautifulSoup(all_text)
print all_soup
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.