Python Beautifulsoup循环

发布于 2025-02-12 22:30:17 字数 319 浏览 0 评论 0原文

我正在尝试从A for Loop的特定迭代(在“位置”变量中)分配到使用Beautifutsoup变量的URL,而我看不出为什么它不起作用(输出是完整列表 - 我只有想要选定的一个)。任何帮助都非常感谢。谢谢!

position = int(input('Enter position:'))
n = int(0)

tags = soup('a')
for tag in tags:
    if n<position:
        n=n+1
    else:
        x=tag.get('href', None)
        print(x)

I'm trying to assign the URL from a specific iteration (in the 'position' variable) of a for loop to a variable using BeautifulSoup, and I can't see why it's not working (the output is the full list - I only want the selected one). Any help wld much appreciated. Thanks!

position = int(input('Enter position:'))
n = int(0)

tags = soup('a')
for tag in tags:
    if n<position:
        n=n+1
    else:
        x=tag.get('href', None)
        print(x)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

情徒 2025-02-19 22:30:17

您可以避免使用汤对象的.select()方法的限制参数的值。

选择返回由CSS选择器列表匹配的元素列表,例如a type Selector选择的锚定标签。限制停止在指定的数字上匹配。 -1索引从返回的列表中返回最后一个匹配,即处于所需位置。 0索引。

position = int(input('Enter position:'))
result = soup.select('a', limit=position)[-1]['href']
print(result)

You could avoid a loop and pass position as value for limit argument with .select() method of soup object.

select returns a list of elements matched by the css selector list passed in e.g. anchor tags selected by a type selector. limit stops matching at the specified number. -1 index returns last match from returned list i.e. at the desired position. 0-indexing.

position = int(input('Enter position:'))
result = soup.select('a', limit=position)[-1]['href']
print(result)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文