【发布时间】:2015-12-28 09:28:07
【问题描述】:
我想使用 BeautifulSoup 并重复检索特定位置的特定 URL。您可以想象有 4 个不同的 URL 列表,每个列表包含 100 个不同的 URL 链接。
我需要始终获取并打印每个列表上的第三个 URL,而前一个 URL(例如第一个列表上的第三个 URL)将导致第二个列表(然后需要获取并打印第三个 URL 等等直到第 4 次检索)。
然而,我的循环只实现了第一个结果(列表 1 上的第三个 URL),我不知道如何将新 URL 循环回 while 循环并继续该过程。
这是我的代码:
import urllib.request
import json
import ssl
from bs4 import BeautifulSoup
num=int(input('enter count times: ' ))
position=int(input('enter position: ' ))
url='https://pr4e.dr-chuck.com/tsugi/mod/python-
data/data/known_by_Fikret.html'
print (url)
count=0
order=0
while count<num:
context = ssl._create_unverified_context()
htm=urllib.request.urlopen(url, context=context).read()
soup=BeautifulSoup(htm)
for i in soup.find_all('a'):
order+=1
if order ==position:
x=i.get('href')
print (x)
count+=1
url=x
print ('done')
【问题讨论】:
标签: python loops url beautifulsoup