Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 我的循环不是';t运行_Python_Loops_For Loop_Beautifulsoup - Fatal编程技术网

Python 我的循环不是';t运行

Python 我的循环不是';t运行,python,loops,for-loop,beautifulsoup,Python,Loops,For Loop,Beautifulsoup,我正在用Python编写一段代码,使用Beautiful soup获取URL中的所有“a”标记,然后使用位置3处的链接并遵循该链接,我将重复此过程大约18次。我包含了下面的代码,该过程重复了4次。当我运行这段代码时,我在结果中得到了相同的4个链接。我应该得到4个不同的链接。我认为我的循环中有问题,特别是在y=url的行中。我需要帮助找出问题所在 import re import urllib from BeautifulSoup import * list1=list() url = 'http

我正在用Python编写一段代码,使用Beautiful soup获取URL中的所有“a”标记,然后使用位置3处的链接并遵循该链接,我将重复此过程大约18次。我包含了下面的代码,该过程重复了4次。当我运行这段代码时,我在结果中得到了相同的4个链接。我应该得到4个不同的链接。我认为我的循环中有问题,特别是在y=url的行中。我需要帮助找出问题所在

import re
import urllib
from BeautifulSoup import *
list1=list()
url = 'https://pr4e.dr-chuck.com/tsugi/mod/python-data/data/known_by_Fikret.html'

for i in range (4):  # repeat 4 times
    htm2= urllib.urlopen(url).read()
    soup1=BeautifulSoup(htm2)
    tags1= soup1('a')
    for tag1 in tags1:
        x2 = tag1.get('href', None)
        list1.append(x2)
    y= list1[2]
    if len(x2) < 3:  # no 3rd link
        break  # exit the loop
    else:
        url=y             
    print y
重新导入
导入URL库
从美联进口*
list1=list()
url='1〕https://pr4e.dr-chuck.com/tsugi/mod/python-data/data/known_by_Fikret.html'
对于范围(4)内的i:#重复4次
htm2=urllib.urlopen(url.read())
soup1=BeautifulSoup(htm2)
tags1=soup1('a')
对于标记1中的标记1:
x2=tag1.get('href',无)
列表1.追加(x2)
y=列表1[2]
如果len(x2)<3:#无第三链路
中断#退出循环
其他:
url=y
打印y

您将继续将找到的第三个链接添加到结果列表中。相反,您应该添加该迭代的第三个链接(即
soup('a')[2]
),然后重新分配url并再次运行

url = 'https://pr4e.dr-chuck.com/tsugi/mod/python-data/data/known_by_Fikret.html'
result = []

for i in range(4):
    soup = BeautifulSoup(urllib.urlopen(url).read())
    links = soup('a')
    for link in links:
        result.append(link)
    try:
        third_link = links[2]['href']
    except IndexError:  # less than three links
        break
    else:
        url = third_link
        print(url)
这在递归函数中实际上非常简单:

def get_links(url):
    soup = BeautifulSoup(urllib.urlopen(url).read())
    links = soup('a')
    if len(links) < 3:
        # base case
        return links
    else:
        # recurse on third link
        return links + get_links(links[2]['href'])
def get_链接(url):
soup=BeautifulSoup(urllib.urlopen(url.read())
链接=汤('a')
如果len(links)<3:
#基本情况
返回链接
其他:
#在第三个链接上递归
返回链接+获取链接(链接[2]['href'])
您甚至可以修改它,以确保不会递归太深

def get_links(url, times=None):
    '''Returns all <a> tags from `url` and every 3rd link, up to `times` deep

    get_links("protocol://hostname.tld", times=2) -> list
    if times is None, recurse until there are fewer than 3 links to be found
    '''

    def _get_links(url, TTL):
        soup = BeautifulSoup(urllib.urlopen(url).read())
        links = soup('a')
        if (times is not None and TTL >= times) or \
           len(links) < 3:
            # base case
            return links
        else:
            return links + _get_links(links[2]['href'], TTL+1)
    return _get_links(url, 0)
def get_链接(url,times=None):
''从'url'和每三个链接返回所有标记,最深为'times'
获取链接(“protocol://hostname.tld,次=2)->列表
如果times为None,则递归直到找到的链接少于3个
'''
定义获取链接(url、TTL):
soup=BeautifulSoup(urllib.urlopen(url.read())
链接=汤('a')
如果(时间不是无且TTL>=时间)或\
len(链接)<3:
#基本情况
返回链接
其他:
返回链接+获取链接(链接[2]['href'],TTL+1)
返回\u获取\u链接(url,0)
您当前的代码
y=list1[2]

只需打印位于
list1
索引2处的URL即可。由于该列表仅附加到,
list[2]
不会更改。如果您想要不同的URL,您应该在每次打印时选择不同的索引。我不确定您试图打印的具体内容,但例如,
y=list1[-1]
最终会打印在该迭代中添加到列表中的最后一个URL(每次都不同)。
如果len(x2)<3
应该是
如果len(list1)<3
,并且
y=list1[2]
应位于该if条件的else部分。我怀疑这是你得到五个相同链接的原因,但这是一个潜在的问题。我尝试了上面所有的解决方案,到目前为止没有一个对我有效。“这快把我逼疯了。”朱莉娅·阿奇:我想我当初误解了你的企图。我目前的答案应该可以解决你的问题(抓取所有链接,然后跟随第三个链接并抓取那里的所有链接。)