用beauthoulsoup获取一条特定的行,然后再次将其插入循环中

2024-03-29 15:21:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用beauthulsoup,我得到带有标签('a')的url。在

现在我的问题是,我不知道如何得到一条线。在

我让用户输入一个特定的行position,以及循环应该运行countrepeat的次数。这将在代码中实现。在

所以我想不出两件事:

  1. 如何才能只得到position行(例如第三行)。在
  2. 我如何将该URL再次实现到循环中,使其跟随该链接

我的代码正在使用:

import urllib.request, urllib.parse, urllib.error
from bs4 import BeautifulSoup
import ssl

# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

url = input('Enter - ')
countrepeat = int(input("Enter repeat number:"))
position = int(input("Enter start position:"))

for i in range(countrepeat):
    html = urllib.request.urlopen(url, context=ctx).read()
    soup = BeautifulSoup(html, 'html.parser')
    tags = soup('a')
    print(tags.get('href'))
    url = tags.get('href')

Tags: 代码importurlsslinputrequesthtmlcontext
1条回答
网友
1楼 · 发布于 2024-03-29 15:21:03

假设position是0索引的,使用soup.findAll('a')[position]来获得汤中的第position个锚。在

要获得锚的href,请使用soup.findAll('a')[position]['href']。在

要让循环在下一个请求中使用此href,请将循环中的url更新为来自锚点的href。在

相关问题 更多 >