Python:将解析的信息返回到列表?

2024-03-29 01:35:15 发布

您现在位置: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 = []

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


page_names()

print files[:]

base = "https://realpython.com/practice/"

print base + files[:]

我试图解析出三个网页文件名并将它们附加到“files”列表中,然后以某种方式将它们附加或添加到基本url的末尾,以便进行简单打印。你知道吗

我尝试过将“base”作为一个单独的项目列表,这样我就可以附加,但是我对Python还比较陌生,我相信我把for语句搞砸了。你知道吗

目前我得到:

print files[:]
TypeError: 'type' object has no attribute '__getitem__'

Tags: textfromhttpsimportcomurlbasehtml
1条回答
网友
1楼 · 发布于 2024-03-29 01:35:15

最后定义了list[:],这是完全错误的,因为list是用于创建实际列表的内置关键字。你知道吗

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 = []

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


page_names()


base = "https://realpython.com/practice/"
for i in files:
    print base + i

输出:

https://realpython.com/practice/aphrodite.html
https://realpython.com/practice/poseidon.html
https://realpython.com/practice/dionysus.html

而且您不需要创建中间列表来存储链接或文件,只需使用列表即可。你知道吗

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)
files = [i['href'] for i in soup.find_all('a', href = True)]
base = "https://realpython.com/practice/"
for i in files:
    print base + i

相关问题 更多 >