Python Beautifulsoup循环
我正在尝试从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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以避免使用汤对象的.select()方法的限制参数的值。
选择返回由CSS选择器列表匹配的元素列表,例如
a
type Selector选择的锚定标签。限制停止在指定的数字上匹配。 -1索引从返回的列表中返回最后一个匹配,即处于所需位置。 0索引。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.