gpt4 book ai didi

python - 从 beautifulsoup 的列表中选择链接

转载 作者:行者123 更新时间:2023-12-01 09:07:26 24 4
gpt4 key购买 nike

我正在尝试从 2000 多个项目长的列表中选择链接。最后,我希望能够点击列表中的链接并打开下一页。我可以让 beautiful soup 打印我想要的 li 列表,但我不知道如何跟踪链接。在下面的代码末尾,我尝试添加以下内容:

for link in RHAS:
print(link.get('href'))

但我收到此错误:

AttributeError:“NavigableString”对象没有属性“get”

我认为这与 HTML 仍然附加到代码有关(即,当我打印 li 时,代码中显示 a、li 和 HREF 标签)。我如何让它跟随链接?

from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup


# The website I am starting at
my_url = 'https://mars.nasa.gov/msl/multimedia/raw/'

#calls the urlopen function from the request module of the urllib module
#AKA opens up the connection and grabs the page
uClient = uReq(my_url)

#imports the webpage from html format into python.
page_html = uClient.read()

#closes the client
uClient.close()

#parses the HTML using bs4
page_soup = soup(page_html, "lxml")

#finds the categories for the types of images on the site, category 1 is
#RHAZ
containers = page_soup.findAll("div", {"class": "image_list"})

RHAZ = containers[1]

# prints the li list that has the links I want
for child in RHAZ:
print(child)

最佳答案

子节点包含所有 div、ul、li、a 标签,这就是您收到错误的原因。

如果您想从所有 anchor 标记获取href,请找到所有 anchor 标记并从中提取href,如下所示。

for link in RHAZ.findAll('a'):
print(link['href'])
print(link['href'], link.text) # if you need both href and text

P.S.:您可以解释您正在处理的场景,然后显示您面临的错误,而不是先声明错误并解释您的场景。这会更加清晰,你会很容易得到正确的回应。

关于python - 从 beautifulsoup 的列表中选择链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51939159/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com