如何迭代链接并在特定位置访问一个?



我正在做一个任务,我需要使用BeautifulSoup解析这个:http://python-data.dr-chuck.net/known_by_Fikret.html

基本上,我需要打印初始URL并在位置3找到URL,访问该URL并在该页面的位置3找到链接,等等——这需要总共花费请四次。

这是我到目前为止的代码:

# http://www.py4e.com/code3/bs4.zip
# and unzip it in the same directory as this file
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 - ')
url =  "http://py4e-data.dr-chuck.net/known_by_Fikret.html"
timesToRepeat = '4'
positionInput = '3'
#timesToRepeat = input('Repeat how many times?: ')
#positionInput = input('Enter Position: ')
try:
timesToRepeat = int(timesToRepeat)
positionInput = int(positionInput)
except:
print("please add an number")
quit()
# Retrieve all of the anchor tags
totalCount = 0
currentRepetitionCount = 0
html = urllib.request.urlopen(url, context=ctx).read()
soup = BeautifulSoup(html, 'html.parser')
tags = soup('a')
#Leave this all alone ^^^^
print("Retrieving: ",url)
for i in range(timesToRepeat):
html = urllib.request.urlopen(url, context=ctx).read()
for tag in tags:
currentRepetitionCount += 1
if not totalCount >= timesToRepeat:
if currentRepetitionCount == positionInput:
#print("current",currentRepetitionCount)
#print("total",totalCount)
#print("Retrieving: ",url)
currentRepetitionCount = 0
totalCount +=1
url = tag.get('href', None)
print("Retrieving: ",url)

我得到这个:

Retrieving:  http://py4e-data.dr-chuck.net/known_by_Fikret.html
Retrieving:  http://py4e-data.dr-chuck.net/known_by_Montgomery.html
Retrieving:  http://py4e-data.dr-chuck.net/known_by_Anona.html
Retrieving:  http://py4e-data.dr-chuck.net/known_by_Zoe.html
Retrieving:  http://py4e-data.dr-chuck.net/known_by_Carmyle.html

但我应该得到的是这个:

Retrieving: http://py4e-data.dr-chuck.net/known_by_Fikret.html
Retrieving: http://py4e-data.dr-chuck.net/known_by_Montgomery.html
Retrieving: http://py4e-data.dr-chuck.net/known_by_Mhairade.html
Retrieving: http://py4e-data.dr-chuck.net/known_by_Butchi.html
Retrieving: http://py4e-data.dr-chuck.net/known_by_Anayah.html

似乎链接没有改变,只是每次都在初始链接上找到第三个位置,我似乎一辈子都无法修复它。

尽量简化您的代码,使您的问题和主要问题得到关注。例如,它不需要对if not totalCount >= timesToRepeat:

进行额外检查

请注意,我在timesToRepeat中添加了一个+1,同时也在循环中请求第一个url,以避免重复。

from bs4 import BeautifulSoup
import requests
url = 'http://py4e-data.dr-chuck.net/known_by_Fikret.html'
timesToRepeat = 4
positionInput = 3
for i in range(timesToRepeat+1):
print(f'Retrieving: {url}')
soup=BeautifulSoup(requests.get(url).text)
tag = soup.select('a')[positionInput-1]
url = tag.get('href')
<<编辑>输出/编辑>
Retrieving: http://py4e-data.dr-chuck.net/known_by_Fikret.html
Retrieving: http://py4e-data.dr-chuck.net/known_by_Montgomery.html
Retrieving: http://py4e-data.dr-chuck.net/known_by_Mhairade.html
Retrieving: http://py4e-data.dr-chuck.net/known_by_Butchi.html
Retrieving: http://py4e-data.dr-chuck.net/known_by_Anayah.html

最新更新